【问题标题】:How to stop diagonal movement - Unity 2d?如何停止对角线移动 - Unity 2d?
【发布时间】:2017-10-02 08:25:58
【问题描述】:

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

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

if (!attacking)
{
    if (Input.GetAxisRaw("Horizontal") > 0.5f || Input.GetAxisRaw("Horizontal") < -0.5f)
    {
        //transform.Translate (new Vector3(Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime, 0f, 0f ));
        myRigidBody.velocity = new Vector2(Input.GetAxisRaw("Horizontal") * currentMoveSpeed, myRigidBody.velocity.y);
        PlayerMoving = true;
        lastMove = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
    }

    if (Input.GetAxisRaw("Vertical") > 0.5f || Input.GetAxisRaw("Vertical") < -0.5f)
    {
        //transform.Translate(new Vector3(0f, Input.GetAxisRaw("Vertical") * moveSpeed * Time.deltaTime, 0f));
        myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, Input.GetAxisRaw("Vertical") * currentMoveSpeed);
        PlayerMoving = true;
        lastMove = new Vector2(0f, Input.GetAxisRaw("Vertical"));
    }
}

【问题讨论】:

  • 添加一对私有变量,还记得之前的值并比较一下吗?您是在寻找有关如何处理此问题的基本想法,还是在编码时遇到问题?

标签: c# unity3d


【解决方案1】:

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

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):

【讨论】:

    猜你喜欢
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多