Unity双跳脚本首次跳跃jumpCount未减1问题求助
问题排查与修复
核心问题分析
- maxJumps=1时触发双跳:
Update中先执行地面检测并重置jumpCount = maxJumps,之后才处理跳跃逻辑。当玩家按下跳跃键触发PerformJump减1后,如果当前帧isGrounded仍为true(比如跳跃瞬间尚未离开地面),jumpCount会被重新设回1,导致可以再次跳跃。 - maxJumps=0时无法跳跃:
jumpCount只在isGrounded为true时赋值,初始值为默认0,maxJumps=0时即使在地面也会把jumpCount设为0,永远满足不了jumpCount>0的跳跃条件。 - 首次跳跃jumpCount未减1:跳跃后被地面检测的重置逻辑覆盖,导致数值未按预期变化。
修复后的代码
public class PlayerMovement : MonoBehaviour { public float moveSpeed = 8f; public float jumpForce = 20f; public Transform groundCheck; public LayerMask groundLayer; public float coyoteTime = 0.2f; public int maxJumps = 2; private Rigidbody2D rb; private bool isGrounded; private float coyoteTimeCounter; private int jumpCount; void Start() { rb = GetComponent<Rigidbody2D>(); jumpCount = maxJumps; // 初始化跳跃次数 } void Update() { // 水平移动 float moveInput = Input.GetAxis("Horizontal"); rb.velocity = new Vector2(moveInput * moveSpeed, rb.velocity.y); // 地面检测:记录上一帧状态,避免跳跃瞬间重置次数 bool wasGrounded = isGrounded; isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.1f, groundLayer); // 郊狼时间与跳跃次数重置 if (isGrounded) { coyoteTimeCounter = coyoteTime; // 仅从空中落地时重置跳跃次数 if (!wasGrounded) { jumpCount = maxJumps; } } else { coyoteTimeCounter -= Time.deltaTime; } // 跳跃处理 if (Input.GetButtonDown("Jump")) { if ((isGrounded || coyoteTimeCounter > 0f) && jumpCount > 0) { PerformJump(); } else if (jumpCount > 0) { PerformJump(); } } Debug.Log("剩余跳跃次数: " + jumpCount); } void PerformJump() { rb.velocity = new Vector2(rb.velocity.x, jumpForce); jumpCount--; coyoteTimeCounter = 0f; } }
关键修改点
- 初始化jumpCount:在
Start方法中设置jumpCount = maxJumps,解决maxJumps=0时初始值异常的问题。 - 添加wasGrounded状态:记录上一帧的地面状态,仅当玩家从空中落地时才重置
jumpCount,避免跳跃瞬间地面检测仍为true导致的跳跃次数被覆盖。
内容的提问来源于stack exchange,提问作者Marcus Hormann
相关产品推荐
相关产品推荐

