简体   繁体   English

在 Unity 2D 中禁用对角线移动(但在两者之间波动)

[英]Disable Diagonal Movement in Unity 2D (but fluctuates between the two)

Okay.好的。 So I understand how to disable diagonal movement, but what I want to do is switch between them for every step.所以我知道如何禁用对角线移动,但我想做的是每一步在它们之间切换。 So If I hold Left and Up, the character with go left one, then up, then left again.因此,如果我按住 Left 和 Up,则字符向左移动,然后向上,然后再次向左。 Kind of like a staircase movement.有点像楼梯运动。 Here's what I've got so far:这是我到目前为止所得到的:

private void Update()
{
    if (!isMoving)
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");

        if (input.y != 0) input.x = 0;

        if (input != Vector2.zero)
        {
            var targetPos = transform.position;
            targetPos.x += input.x;
            targetPos.y += input.y;

            StartCoroutine(Move(targetPos));
        }
    }
}

IEnumerator Move(Vector3 targetPos)
{
    isMoving = true;

    while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
        yield return null;
    }
    transform.position = targetPos;

    isMoving = false;
}

Replacing this code snippet will solve the problem completely.替换此代码段将完全解决问题。

public bool phase;
private void Update()
{
    if (!isMoving)
    {
        input.x = Input.GetAxisRaw("Horizontal");
        input.y = Input.GetAxisRaw("Vertical");
        
        if (input != Vector2.zero)
        {
            var targetPos = transform.position;

            if (phase) targetPos.x += input.x;
            else targetPos.y += input.y;

            StartCoroutine(Move(targetPos));

            phase = !phase;
        }
    }
}

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM