[英]#Unity Cube Movement (Jumping +1 Forward/Right/Backward/Left)
嘿stackoverflow社区,
首先:
我的问题:我正在研究一个立方体运动的想法。 计划通过按一个键(W-Key)使立方体向前移动。 但它不应该只是向前推进。 它应该向前跳到下一点。 因此,始终将其轴的 1 加到 go 中。 因此,它仅用于 go 向前、向右、向下、向左。 他不能从后面跳过去。 您还应该看到立方体在各自的方向上跳跃,因此它不应该自行传送。 :D
有谁知道我如何实现这一运动? 我非常期待您的想法。
(对不起,如果我的英语不是那么好,我的英语不是最好的。^^)
最好的问候 xKarToSx
因此,为了理解运动,最好先了解 Unity 中的向量。 由于您想向前移动立方体,我将假设这是一个 3D 游戏,在这种情况下您想使用 Vector3。
Vector3 具有三个分量:X、Y 和 Z。每个分量都与一个轴相关联。 简单来说,X系左右,Y系上下,Z系前后。 所以, Vector3 position = new Vector3(0, 1, 2);
将是一个在起始 position 上方 1 个单位和 2 个单位前的向量。
假设您已将此脚本附加到要移动的多维数据集,您可以使用transform.position
跟踪其 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。 基本上,您可以使用它在两个定义的位置之间平滑过渡 object。 您需要实现一个计时器和一个 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
}
}
我希望这可以帮助你。 这是我第一次回答一个问题,如果我弄错了/它不是最优化的,很抱歉。 祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.