c# - 如何让物体自己移动?

标签 c# unity3d

我是 unity3d 的新手,我正在一步步自学。不过我遇到了障碍。我想为这个我称之为“敌人”的球体写一个脚本,我希望它以一种模式移动,例如。 forwards500 -sideways(left)500 -forwards(backward)500 sideways500 forwards500.

我该怎么做才能按顺序调用每个步骤?谢谢

最佳答案

(在我看来)最好的控制方式是 Coroutine :

[Tooltip("Adjust how fast you want to move (units/second)")]
[SerilaizeField] private float moveSpeed;

[Tooltip("Fill this with your desired move steps")]
// via the INSPECTOR in Unity! (later changes here in code will have no effect!)
[SerializeField] private Vector3[] moveSteps = new []
{
    Vector3.forwards * 500,
    Vector3.left * 500,
    Vector3.backwards * 500,
    Vector3.right * 500
};

// Yes, this is possible!
// If start is an IEnumerator it is automatically started as Coroutine by Unity
private IEnumerator Start()
{
    // This looks creepy but is fine in an 
    // IEnumerator as long as you yield somewhere within!
    while(true)
    {
        // iterate through the array of movements
        foreach(var step in moveSteps)
        {
            var currentTargetPosition = transform.position + step;

            // This checks if the two positions match "exactly"
            // If it is enough that the positions match up to a precision of 0.00001 
            // it would be more efficient to simply compare 
            //while(transform.position != currentTargetPosition)
            while(!Mathf.Approximately(Vector3.Distance(transform.position, currentTargetPosition), 0f))
            {
                // move one step towards the current target position 
                // without overshooting
                transform.position = Vector3.MoveTowards(transform.position, currentTargetPosition, moveSpeed * Time.deltaTime);

                // Tells Unity to "pause" here, render this frame and 
                // continue from here in the next frame
                yield return null;
            }

            // to be sure to reach sharp positions set the target fix
            transform.position = currentTargetPosition;
        }
    }
}

这将使用配置的 moveSteps 作为模式,以moveSpeed恒定 速度将对象从一个目标位置移动到下一个目标位置。


如果你更愿意向“边缘”添加一些缓入和缓出,你也可以做类似的事情

private IEnumerator Start()
{
    while(true)
    {
        foreach(var step in moveSteps)
        {
            var currentPosition = transform.position;
            var currentTargetPosition = currentPosition + step;

            // Get the expected move duration according to the speed
            var duration = Vector3.Distance(transform.position, currentTargetPosition) / moveSpeed;

            var timePassed = 0f;
            while(timePassed < duration)
            {
                // Get a factor betwwen 0 and 1
                var factor = timePassed / duration;
                // add easing 
                factor = Mathf.SmoothStep(0, 1, factor);                    

                // Interpolate the position between the start and endpoint
                transform.position = Vector3.Lerp(currentPosition, currentTargetPosition, factor);

                // increase by the time passed since last frame
                timePassed += Time.deltaTime;
                yield return null;
            }

            // to be sure to reach sharp positions set the target fix
            transform.position = currentTargetPosition;
        }
    }
}

关于c# - 如何让物体自己移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63106903/

相关文章:

java - Unity-Android _ CommandInvokationFailure : Unable to convert classes into dex format

c# - WPF RichTextBox 增量字体大小

C# - 比较两个 CSV 文件并给出输出

c# - FormsAuthentication.SignOut() 使用 javascript

c# - 我将如何对这种方法进行单元测试?

audio - 如何添加2种声音并通过脚本播放它们?

c# - 将我的应用程序时间与外部服务器时间同步的最佳方法是什么?

c# - 统一 5 : How to pass multiple parameters on button click function from inspector?

c# - 确定在 Unity C# 中顺时针还是逆时针旋转更快

android - 用户退出 Google Play 服务后保存游戏的最佳做法?