我正在尝试制作一个移动脚本,其中角色从一侧移动到另一侧并且它只停留在屏幕的一侧......(Unity 2D)

I'm trying to make a movement script where the character moves from side to side and it just stays to one side of the screen... (Unity 2D)

这是我的代码,如果它对任何人有帮助... 我真的不知道它有什么问题,但是当我在网上搜索答案时,没有任何帮助。这都是玩家控制的脚本,而不是我可以使用的任何东西。任何帮助将不胜感激,谢谢。 '''

[HideInInspector] public bool moving;
[HideInInspector] public int direction;
public float restTime;
public float speed = 0.1f;
private float maxX = 2f;
private float minX = -2f;
private float currentX;
void Start()
{
    SpriteAnimator animator = gameObject.GetComponent<SpriteAnimator>();
    currentX = gameObject.transform.position.x;
    string message = "Moving: " + moving + ", Dirrection: " + direction + ", Current X: " + currentX;
    Debug.Log(message);
}
void Update()
{
    if (restTime > 0f)
    {
        restTime -= Time.deltaTime;
    }
    else
    {
        if (direction == 0 && currentX < minX)
        {
            moving = true;
            while (currentX >= minX)
            {
                currentX = gameObject.transform.position.x;
                gameObject.transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f);
            }
            moving = false;
            restTime = 5f;
        }
        else
        {
            moving = true;
            while (currentX <= maxX)
            {
                currentX = gameObject.transform.position.x;
                gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
            }
            moving = false;
            restTime = 5f;
        }
    }
}

'''

乍一看,if (direction == 0 && currentX < minX) 应该是 if (direction == 0 && currentX > minX)。我看到的另一个问题是,每一帧都会看到对象在一侧或另一侧,而在两个位置之间的位置没有帧。如果这是为了始终 运行 并且对象几乎不断地在屏幕上来回移动,我建议您尝试这样做。

IEnumerator MoveObject() {
    while(true) {
        if(direction == 0) {
            while(currentX >= minX) {
                gameObject.transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f);
                currentX = gameObject.transform.position.x;
                yield return null; // waits for the next frame before continuing
            }
            direction == 1;
        } else {
            while(currentX <= maxX) {
                gameObject.transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
                currentX = gameObject.transform.position.x;
                yield return null; // waits for the next frame before continuing
            }
            direction == 0;
        }
        yield return new WaitForSecondsRealtime(5f); // how long to wait before continuing
        // If you want to allow for the "pausing" of the coroutine by modifying the passage of in-game time, you would call
        // yield return new WaitForSeconds(5f);
    }
}

您可以从启动方法中调用它,如下所示

private void Start() {
    // Other Code Here //
    _= StartCoroutine(MoveObject());
}