You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity2D C# 角色跳跃功能异常求助:无法实现单次跳跃

平台游戏角色单次跳跃问题解决方案

原代码核心问题

  • 重复监听跳跃输入:同时通过Input.GetButtonDown("Jump")和Input.GetKeyDown(KeyCode.Space)触发跳跃,后者未做接地判断,直接导致空中无限跳
  • 跳跃逻辑冲突:分别用rb.velocity和rb.AddForce两种方式施加跳跃力,相互干扰导致跳跃行为异常

修复后的完整代码

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    private float horizontal;
    [SerializeField] private float speed = 5f;
    [SerializeField] private float jumpingPower = 15f;
    private bool isFacingRight = true;

    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    void Update()
    {
        horizontal = Input.GetAxisRaw("Horizontal");

        // 单次跳跃逻辑:仅接地时可跳
        if (Input.GetButtonDown("Jump") && IsGrounded())
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
        }

        // 跳顶轻触减速:提升跳跃手感
        if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
        {
            rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
        }

        Flip();
    }

    private void FixedUpdate()
    {
        // 仅处理水平移动,不干扰垂直方向速度
        rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
    }

    // 检测是否接地:用圆形碰撞器检测地面层
    private bool IsGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    // 角色翻转逻辑
    private void Flip()
    {
        if ((isFacingRight && horizontal < 0f) || (!isFacingRight && horizontal > 0f))
        {
            isFacingRight = !isFacingRight;
            Vector3 localScale = transform.localScale;
            localScale.x *= -1f;
            transform.localScale = localScale;
        }
    }
}

关键注意事项

  • 确保groundCheck对象位于角色底部合适位置,圆形检测半径0.2f需根据角色大小调整
  • groundLayer必须正确赋值为场景中的地面图层,避免误检测其他物体
  • 保持输入逻辑统一:优先使用Unity Input Manager中的虚拟轴(如"Jump"),而非直接监听按键,便于后续调整控制方案

内容的提问来源于stack exchange,提问作者J Harkness

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:50:45