[英]How to stop diagonal movement - Unity 2d?
这是我在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"));
}
}
这是我的处理方式:当只有一个轴处于活动状态(水平或垂直)时,请记住该方向。 如果两者都存在,则优先考虑不是的优先级。 以下代码完全按照您的描述工作,但必须适应您的其他要求。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.