コード例 #1
0
    IEnumerator FollowPath()
    {
        Vector3 movementDir;
        int     curWaypointNodeIndex = 1;
        Node    curWaypointNode      = path[curWaypointNodeIndex];

        // Make sure we let the entityMovement component know that it's good to move
        entityMovement.CanMove(true);

        // Since we are on a grid we can zero out the y position for nodes and entities
        Vector3 curEntityPosition       = new Vector3(transform.position.x, 0.0f, transform.position.z);
        Vector3 curWaypointNodePosition = new Vector3(curWaypointNode.position.x, 0.0f, curWaypointNode.position.z);

        // Move towards the starting node
        movementDir = (curWaypointNodePosition - curEntityPosition).normalized;
        entityMovement.UpdateTargetMovementDirection(movementDir);

        while (true)
        {
            curEntityPosition = new Vector3(transform.position.x, 0.0f, transform.position.z);

            // If our current position is near the current node we're moving towards ...
            if ((curWaypointNodePosition - curEntityPosition).magnitude <= 0.1f)
            {
                // ... iterate the waypoint node index ...
                curWaypointNodeIndex++;

                // ... check if we have reached the goal node ...
                if (curWaypointNodeIndex >= path.Count)
                {
                    entityMovement.StopMoving();
                    yield break;
                }

                // ... update curWaypointNode to the new waypoint node ...
                curWaypointNode = path[curWaypointNodeIndex];

                // .. update our local position vector ...
                curWaypointNodePosition.x = curWaypointNode.position.x;
                curWaypointNodePosition.z = curWaypointNode.position.z;
            }

            // ... update out movement direction.
            movementDir = (curWaypointNodePosition - curEntityPosition).normalized;
            entityMovement.UpdateTargetMovementDirection(movementDir);

            Debug.DrawRay(transform.position, movementDir);

            yield return(null);
        }
    }