在统一的y轴(下降)转换位置

我想要按下一个按键,而不是重复按下按键,使gameobject向下(position.y)。 所以在我现在的代码中,每当我按下一个键时,对象就会下降(0.05f)。 但是当我按下一个键的时候,我希望它能顺利的animation下去(1.2)。

Vector2 Pos; void Update () { Pos = transform.position; if(Input.anyKeyDown) { ChangePosY(); } transform.position = Pos; } void ChangePosY() { if (Pos.y >= 1.2) { Pos.y -= 0.05f; } } 

您可以使用Vector2.Lerp()平滑翻译。 一个新的variablesisKeyPressed用于检测当目标位置条件满足时改变的按键,直到以0.1的频率在y轴/向下以1.2单位向目标位置平移。 参见Lerp()Ref。

 Vector2 Pos; bool isKeyPressed = false; void Update() { Pos = transform.position; if (Input.anyKeyDown) { isKeyPressed = true; } if (isKeyPressed) { ChangePosY(); } transform.position = Pos; } void ChangePosY() { if (Pos.y >= 1.2f) { Pos = Vector2.Lerp(Pos, new Vector2(Pos.x, Pos.y - 1.2f), 0.1f); } else { isKeyPressed = false; } } 

我会用一个协程来做到这一点:

 // Keep track of the current coroutine so we don't stack up multiple. Coroutine translation; void Update() { if(Input.anyKeyDown) { translation = StartCoroutine( TranslateTo( /* Put the final position you want here */, 1.0f ) ); } } IEnumerator TranslateTo(Vector3 destination, float duration) { // Stop previous coroutine if the last motion didn't finish yet. if(translation != null) StopCoroutine(translation); Vector3 initialPosition = transform.position; // Shifting the start back one frame so we move a little immediately. float startTime = Time.time - Time.deltaTime; float endTime = startTime + duration; while(Time.time < endTime) { float t = (Time.time - startTime)/duration; transform.position = Vector3.Lerp(initialPosition, destination, t); // Wait one frame, then resume here. yield return null; } // Ensure we finish exactly at the destination. transform.position = destination; // Clear coroutine cache to signal that we're done. translation = null; }