如何通过方法调用使GameObject相对于自身移动一些固定单位

时间:2019-07-16 22:23:41

标签: c# unity3d

我想要的是,每次调用MoveTile(Direction direction)时,绿点(这是一个附带脚本的GameObject)都会移动一个红色的移动箭头,例如MoveTile(Direction.EAST);

因此,如果在时间点A的时间MoveTile(Direction.EAST);被调用,并且在时间B的时间MoveTile(Direction.NORTH);被调用,您应该得到以下结果:

Explanatory image of movement

绿点当前附加了以下MonoBehaviour:

public class PlayerIndicator : MonoBehaviour
{
    public enum Direction { NORTH, EAST, SOUTH, WEST }
    private static readonly int TILE_UNIT = 2;

    public void MoveTile(Direction direction)
    {
        switch (direction)
        {
            case Direction.NORTH:
                // TODO move one TILE_UNIT up
                break;
            case Direction.EAST:
                // TODO move one TILE_UNIT right
                break;
            case Direction.SOUTH:
                // TODO move one TILE_UNIT down
                break;
            case Direction.WEST:
                // TODO move one TILE_UNIT left
                break;
        }
    }
}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我知道了。通过将协程与阈值检查结合使用,您可以移动直到到达所需位置。

public class PlayerIndicator : MonoBehaviour
{
    public enum Direction { NORTH, EAST, SOUTH, WEST }
    private static readonly float SPEED = 1f;
    private static readonly float THRESHOLD = 0.01f;
    private static readonly float TILE_DISTANCE = 2f;

    private void Update()
    {
        // Fire coroutine, this can also be done with an event
        StartCoroutine(MoveTileOverTime(Direction.EAST));
    }

    public IEnumerator MoveTileOverTime(Direction direction)
    {
        Vector2 target = new Vector2();

        // Determine the target position, this is relative from the current position
        switch (direction)
        {
            case Direction.NORTH:
                target = (Vector2) transform.position + Vector2.up * TILE_DISTANCE;
                break;
            case Direction.EAST:
                target = (Vector2) transform.position + Vector2.right * TILE_DISTANCE;
                break;
            case Direction.SOUTH:
                target = (Vector2) transform.position + Vector2.down * TILE_DISTANCE;
                break;
            case Direction.WEST:
                target = (Vector2) transform.position + Vector2.left * TILE_DISTANCE;
                break;
        }

        // Threshold check / stop condition
        while (Vector2.Distance(transform.position, target) > THRESHOLD)
        {
            transform.position = Vector2.MoveTowards(transform.position, target, Time.deltaTime * SPEED);
            // All coroutines MUST end with a yield
            yield return new WaitForEndOfFrame();
        }
    }
}