[英]Disable Diagonal Movement in Unity 2D (but fluctuates between the two)
好的。 所以我知道如何禁用對角線移動,但我想做的是每一步在它們之間切換。 因此,如果我按住 Left 和 Up,則字符向左移動,然后向上,然后再次向左。 有點像樓梯運動。 這是我到目前為止所得到的:
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;
}
替換此代碼段將完全解決問題。
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.