如何阻止对角线运动 - Unity 2d?

时间:2017-10-02 08:25:59

标签: c# unity3d

这是我在Unity(2d)中玩家移动的脚本。

当按下两个方向键 - 而不是对角线移动 - 我需要玩家在最近按下的方向移动(如果释放,则已经按下方向)

new Tree[]{m,p}

1 个答案:

答案 0 :(得分:2)

以下是我将如何处理它:当只有一个轴处于活动状态(水平或垂直)时,请记住该方向。当两者都是时,优先考虑那个没有的那个。以下代码与您描述的完全一致,但必须根据您的其他要求进行调整。

void Update()
{
    float currentMoveSpeed = moveSpeed * Time.deltaTime;

    float horizontal = Input.GetAxisRaw("Horizontal");
    bool isMovingHorizontal = Mathf.Abs(horizontal) > 0.5f;

    float vertical = Input.GetAxisRaw("Vertical");
    bool isMovingVertical = Mathf.Abs(vertical) > 0.5f;

    PlayerMoving = true;

    if (isMovingVertical && isMovingHorizontal)
    {
        //moving in both directions, prioritize later
        if (wasMovingVertical)
        {
            myRigidBody.velocity = new Vector2(horizontal * currentMoveSpeed, 0);
            lastMove = new Vector2(horizontal, 0f);
        }
        else
        {
            myRigidBody.velocity = new Vector2(0, vertical * currentMoveSpeed);
            lastMove = new Vector2(0f, vertical);
        }
    }
    else if (isMovingHorizontal)
    {
        myRigidBody.velocity = new Vector2(horizontal * currentMoveSpeed, 0);
        wasMovingVertical = false;
        lastMove = new Vector2(horizontal, 0f);
    }
    else if (isMovingVertical)
    {
        myRigidBody.velocity = new Vector2(0, vertical * currentMoveSpeed);
        wasMovingVertical = true;
        lastMove = new Vector2(0f, vertical);
    }
    else
    {
        PlayerMoving = false;
        myRigidBody.velocity = Vector2.zero;
    }
}

示例结果(粉色线为lastMove): Result