C# #统一立方体移动(向前/向右/向后/向左跳跃+;1)

C# #统一立方体移动(向前/向右/向后/向左跳跃+;1),c#,unity3d,scripting,game-engine,game-development,C#,Unity3d,Scripting,Game Engine,Game Development,嘿,我的社区 首先: 我对使用C#和Unity编程仍然很陌生 我的问题: 我正在构思一个立方体的运动。 按计划,立方体将通过按键(W键)向前移动。但它不应该只是向前推进。它应该向前跳到下一点。所以总是加上它应该进入的轴的1。因此,它仅用于向前、向右、向下、向左。他不能从后面跳过去。您还应该看到立方体在各自的方向上跳跃,因此它不应该传送自身D 有人知道我如何实现这一运动吗? 我非常期待你的想法 (对不起,如果我的英语不是很好,我的英语不是最好的。^) 致意 所以,为了理解运动,最好首先理解统一

嘿,我的社区

首先:

  • 我对使用C#和Unity编程仍然很陌生
我的问题: 我正在构思一个立方体的运动。 按计划,立方体将通过按键(W键)向前移动。但它不应该只是向前推进。它应该向前跳到下一点。所以总是加上它应该进入的轴的1。因此,它仅用于向前、向右、向下、向左。他不能从后面跳过去。您还应该看到立方体在各自的方向上跳跃,因此它不应该传送自身D

有人知道我如何实现这一运动吗? 我非常期待你的想法

(对不起,如果我的英语不是很好,我的英语不是最好的。^)

致意
所以,为了理解运动,最好首先理解统一的向量。因为你想向前移动立方体,我假设这是一个3D游戏,在这种情况下你想使用矢量3

矢量3有三个分量:X、Y和Z。每个分量都与一个轴相连。简单地说,X与左右、Y与上下、Z与前后相连。所以,
Vector3位置=新的Vector3(0,1,2)将是一个向量,在起始位置上方1个单位,在起始位置前方2个单位

假设已将此脚本附加到要移动的多维数据集,则可以使用
transform.position
跟踪其位置。因此,如果要将多维数据集向前移动一个单位,则代码如下所示:

if(Input.GetKeyDown(KeyCode.W))//一旦用户按下W,此代码将被激活。
{
transform.position+=新向量3(0,0,1);
}

这将使立方体沿Z方向向前移动一个单位。但是,你不想让它传送,你想看到它移动,对吗?在这种情况下,您需要检查Unity,基本上,您可以使用它在两个定义的位置之间平滑地转换对象。您需要实现一个计时器和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
    }
}

我希望这对你有帮助。这是我第一次回答一个问题,很抱歉,如果我弄错了/这不是最优化的。祝你好运

欢迎来到SO。有很多方法可以实现这一点。你能展示你的作品吗?到目前为止你都做了些什么?我建议你在youtube上学习这方面的教程。有很多简单的教程,您可以在其中学习代码。这些都是理想的起点。例如: