【发布时间】:2020-05-15 23:22:55
【问题描述】:
我有一些代码可以让玩家上下左右移动。
public class playerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Animator animator;
public SpriteRenderer sr;
Vector2 movement;
bool walking = false;
private void Update()
{
//Inputs
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
if (Input.GetKey("left") || Input.GetKey("right") || Input.GetKey("up") || Input.GetKey("down")
{
walking = true;
}
else
{
walking = false;
}
Animate();
}
private void Animate()
{
if (Input.GetKey("down") && walking == false)
{
sr.flipX = false;
animator.Play("idle_front");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_front");
}
else if (Input.GetKey("up") && walking == false)
{
sr.flipX = false;
animator.Play("idle_back");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_back");
}
else if (Input.GetKey("left") && walking == false)
{
sr.flipX = false;
animator.Play("idle_side");
}
else if (Input.GetKey("down") && walking)
{
sr.flipX = false;
animator.Play("walk_side");
}
else if (Input.GetKey("right") && walking == false)
{
sr.flipX = true;
animator.Play("idle_side");
}
else if (Input.GetKey("right") && walking)
{
sr.flipX = true;
animator.Play("walk_side");
}
}
public void FixedUpdate()
{
//Movement
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
}
}
动作运行良好,但角色只是停留在空闲状态。
我尝试将Input.GetKey("left") || Input.GetKey("right") || Input.GetKey("up") || Input.GetKey("down") 中的get 键切换为Input.GetKeyDown() 和Input.GetKeyUp(),但这些都不起作用。
我也尝试过使用混合树,但我不知道该怎么做。
我对 Unity 还很陌生,所以一个简单的答案会很棒。
【问题讨论】:
-
提问前请阅读[提问指南] (stackoverflow.com/help/how-to-ask)。关于问题,有大量的 youtube 视频。你尝试过其中任何一个吗?只需 3 个字,您就可以找到解决方案。这是其中之一的链接。 Unity 2D Character Animation