0

我正在练习创建 2D 游戏,我编写了 C# 脚本代码,但我的角色无法跳跃。

我尝试用同样不起作用的“UpArrow”替换“Space”。

if (Input.GetKey(KeyCode.UpArrow) && onGround)
 {
 rb.velocity = new Vector2(rb.velocity.x, jumppower);
 }

什么都没发生。角色可以左右移动但不能跳跃。

4

1 回答 1

0

一些项目开始:

  1. 确保 onGround 为真。=>Debug.Log($"is on ground {onGround}")在 if 之前添加 a 并检查它。
  2. 确保代码在 Update() 循环中(您也可以在 FixedUpdate 中设置它,但更新更好)

然后我看到一个逻辑问题。这是您的代码中发生的情况:

  • 你在地上
  • 你增加速度并向上移动
  • 你已经不在地上了
  • if 失败,所以垂直速度停止,因为你不再在地面上
  • 玩家后退

要解决此问题,请替换此行:

rb.velocity = new Vector2(rb.velocity.x, jumppower);

有了这个:

rb.AddForce(new Vector2(0, jumppower), ForceMode2D.Impulse);
于 2019-05-14T16:11:25.227 回答