Unity C#:跨定义路径移动对象时出现问题

我正在尝试使用以下脚本沿从一个点到另一点的路径创建运动:

using UnityEngine;
public class FollowThePath : MonoBehaviour {

// Array of waypoints to walk from one to the next one
[SerializeField]
private Transform[] waypoints;

// Walk speed that can be set in Inspector
[SerializeField]
private float moveSpeed = 2f;

// Index of current waypoint from which Enemy walks
// to the next one
private int waypointIndex = 0;

// Use this for initialization
private void Start () {

    // Set position of Enemy as position of the first waypoint
    transform.position = waypoints[waypointIndex].transform.position;
}

// Update is called once per frame
private void Update () {

    // Move Enemy
    Move();
}

// Method that actually make Enemy walk
private void Move()
{
    // If Enemy didn't reach last waypoint it can move
    // If enemy reached last waypoint then it stops
    if (waypointIndex <= waypoints.Length - 1)
    {

        // Move Enemy from current waypoint to the next one
        // using MoveTowards method
        transform.position = Vector2.MoveTowards(transform.position,
           waypoints[waypointIndex].transform.position,
           moveSpeed * Time.deltaTime);

        // If Enemy reaches position of waypoint he walked towards
        // then waypointIndex is increased by 1
        // and Enemy starts to walk to the next waypoint
        if (transform.position == waypoints[waypointIndex].transform.position)
        {
            waypointIndex += 1;
        }
    }
}

}

但是,无论我尝试了什么,都不会触发此部分:

if (transform.position == waypoints[waypointIndex].transform.position)
        {
            waypointIndex += 1;
        }

仅当我将其放在movs函数之前的update()中时,它才会被触发。如果我在update()中的move函数之后添加它,它将永远不会被触发,并且对象也不会像其原始形式那样运动。

我在这里做错了什么?

评论
afuga
afuga

如果您使用更改字符位置

moveSpeed * Time.deltaTime

该位置将与数组的任何位置都不完全匹配,因为Time.deltaTime是自上一帧以来的时间,并且它是一个浮动的浮点数,带有许多十进制数。这会使位置不完全相同,因此不会触发您感兴趣的代码部分。 如果您之前放过它,那它就行得通,因为在start()已经在您路径的确切位置,条件是正确的。

对于要满足的最后一个条件,您必须通过路径的确切点来更新路径上的字符位置,从而增加waypoints [waypointIndex]的索引,而不是使用Time.deltaTime。

对于路径跟踪,我建议使用Itween插件,它易于使用,可以具有很酷的弯曲路径跟踪,并易于理解实现。

https://assetstore.unity.com/packages/tools/animation/itween-84

如果您有兴趣,我可以提供一个试用脚本,对您有帮助。

希望能有所帮助。

点赞
评论
quo_et
quo_et

Nested if in some functions sometimes give some errors. Have u tried to use a print method to see that whether your function goes inside of the second if statement or not. If you haven't, try that. And also, create another method and get a parameter which is in this case for your code is waypointIndex then try to call that inside of the Move method.

点赞
评论