我正在 Unity 中制作一个 2D 游戏,玩家可以向左或向右跳跃和行走。玩家应该能够在半空中改变方向,但问题是,尽管不再按移动键,但他们仍继续朝跳跃时移动的方向移动。
这是运动脚本:
public float jumpHeight;
public float speed;
public Rigidbody2D rb;
private bool isGrounded;
public Transform feetPos;
public float checkRadius;
public LayerMask Ground;
private float jumpTimeCounter;
public float jumpTime;
private bool isJumping;
void Update()
{
PausedThisFrame = false;
isGrounded = Physics2D.OverlapCircle(feetPos.position, checkRadius, Ground);
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
isJumping = true;
jumpTimeCounter = jumpTime;
rb.velocity = Vector2.up * jumpHeight;
}
if (Input.GetKey(KeyCode.Space) && isJumping)
{
if (jumpTimeCounter > 0)
{
rb.velocity = Vector2.up * jumpHeight;
jumpTimeCounter -= Time.deltaTime;
}
else
{
isJumping = false;
}
}
if (Input.GetKeyUp(KeyCode.Space))
{
isJumping = false;
}
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.A))
{
Debug.Log("A");
rb.velocity = new Vector2(-1 * speed, rb.velocity.y);
transform.eulerAngles = new Vector3(0, 180, 0);
}
if (Input.GetKey(KeyCode.D))
{
Debug.Log("D");
rb.velocity = new Vector2(1 * speed, rb.velocity.y);
transform.eulerAngles = new Vector3(0, 0, 0);
}
else
{
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y);
}
}
我尝试调试代码以查看脚本是否认为按键被按下,但即使脚本也知道它们没有被按下,所以我真的不知道是什么改变了刚体的速度。
else
{
rb.velocity = new Vector2(0, rb.velocity.y);
}
将水平速度设置为零