【问题标题】:#Unity Cube Movement (Jumping +1 Forward/Right/Backward/Left)#Unity Cube 运动(向前/向右/向后/向左跳跃 +1)
【发布时间】:2020-02-11 00:04:54
【问题描述】:

嘿 stackoverflow 社区,

首先:

  • 我对使用 C# 和 Unity 进行编程还是很陌生。

我的问题: 我正在研究一个立方体运动的想法。 计划通过按一个键(W-Key)使立方体向前移动。但它不应该只是向前推进。它应该向前跳到下一点。所以总是加上它应该进入的轴的 1。因此,它只打算向前、向右、向下、向左。他不能从后面跳过去。您还应该看到立方体在各自的方向上跳跃,因此它不应该自行传送。 :D

有谁知道我如何实现这个运动? 我非常期待您的想法。

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

最好的问候 xKarToSx

【问题讨论】:

  • 欢迎来到 SO。有很多方法可以实现这一点。你能展示你的作品吗?到目前为止,您尝试过什么?
  • 我建议您遵循 youtube 教程。有很多简单的教程,您可以在其中学习代码。这些都是理想的起点。例如:youtube.com/watch?v=sXQI_0ILEW4

标签: c# unity3d scripting game-engine game-development


【解决方案1】:

所以,为了理解运动,最好先了解 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
    }
}

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

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多