所以,为了理解运动,最好先了解 Unity 中的向量。由于您希望正向移动立方体,我将假设这是一个 3D 游戏,在这种情况下您想使用 Vector3。
Vector3 具有三个分量:X、Y 和 Z。每个分量都与一个轴相关联。简单来说,X是左右绑定的,Y是上下绑定的,Z是前后绑定的。因此,Vector3 position = new Vector3(0, 1, 2); 将是一个高于起始位置 1 个单位和高于起始位置 2 个单位的向量。
假设您已将此脚本附加到要移动的立方体上,您可以使用transform.position 跟踪其位置。因此,如果您想将立方体向前移动一个单位,您的代码将如下所示:
if(Input.GetKeyDown(KeyCode.W)) // This code will activate once the user presses W.
{
transform.position += new Vector3(0, 0, 1);
}
这将使立方体在 Z 方向上向前移动一个单位。但是,您不希望它传送,您希望看到它移动,对吗?在这种情况下,您想查看 Unity 的 Vector3.Lerp function. 基本上,您将使用它在两个定义的位置之间平滑地转换对象。您需要实现一个计时器和一个 for 循环才能使其正常工作。
因此,总而言之,要在 Z 方向上向前移动一个单位,您的代码将如下所示:
if(Input.GetKeyDown(KeyCode.Z))
{
float startTime = Time.time; //Time.time is the current in-game time when this line is called. You'll want to save this to a variable
float speed = 1.0f; //The speed if something you'll want to define. The higher the speed, the faster the cube will move.
Vector3 startPosition = transform.position; //Save the starting position to a different variable so you can reference it later
Vector3 endPosition = startPosition + Vector3.forward; //Vector3.Forward is equivalent to saying (0, 0, 1);
float length = Vector3.Distance(startPosition, endPosition); //You'll need to know the total distance that the cube will move.
while(transform.position != endPosition) //This loop while keep running until the cube reaches its endpoint
{
float distCovered = (Time.time - startTime) * speed; //subtracting the current time from your start time and multiplying by speed will tell us how far the cube's moved
float fraction = distCovered / length; //This will tell us how far along the cube is in relation to the start and end points.
transform.position = Vector3.Lerp(startPosition, endPosition, fraction); //This line will smoothly transition between the start and end points
}
}
我希望这对你有帮助。这是我第一次回答一个问题,如果我弄错了/它不是最优化的,很抱歉。祝你好运!