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

Unity 2D平台跳跃问题:空中连跳与墙体卡顿求助

解决Unity 2D平台角色的两个问题:空中连跳与贴墙卡顿

问题1:禁止空中连跳

当前代码只要按下空格就触发跳跃,完全没判断角色是否在地面。我们可以通过射线检测判断角色是否接地,确保只有站在地面时才能跳跃:

  1. 给所有地面对象设置专属Layer(比如命名为"Ground"),让射线只检测地面
  2. 在代码中添加地面检测逻辑,限制跳跃触发条件

问题2:贴墙移动卡顿

直接设置Rigidbody2D.velocity.x会强行覆盖物理引擎的碰撞处理逻辑,导致角色贴墙时和墙面的物理交互冲突,产生卡顿。改用AddForce施加水平力,让物理引擎自然处理碰撞,就能解决卡顿问题。

修改后的完整代码

public class movementSide : MonoBehaviour
{
    [SerializeField] private float speed;
    [SerializeField] private float jumpPower;
    [SerializeField] private float groundCheckDistance; // 射线检测长度,可在Inspector调整
    [SerializeField] private LayerMask groundLayer; // 指定地面Layer
    private Rigidbody2D body;

    private void Awake()
    {
        body = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        // 处理水平移动:用AddForce替代直接设置velocity,避免贴墙卡顿
        float horizontalInput = Input.GetAxis("Horizontal");
        body.AddForce(new Vector2(horizontalInput * speed, 0), ForceMode2D.Force);

        // 限制水平速度,避免无限加速
        if (Mathf.Abs(body.velocity.x) > speed)
        {
            body.velocity = new Vector2(Mathf.Sign(body.velocity.x) * speed, body.velocity.y);
        }

        // 处理跳跃:只有接地时才能跳,用GetKeyDown避免按住空格持续跳跃
        if (Input.GetKeyDown(KeyCode.Space) && IsGrounded())
        {
            body.velocity = new Vector2(body.velocity.x, jumpPower);
        }
    }

    // 检测角色是否接地
    private bool IsGrounded()
    {
        // 从角色中心向下发射射线,检测是否碰到地面
        RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, groundCheckDistance, groundLayer);
        // 可视化射线,方便调试(Scene视图中可见)
        Debug.DrawRay(transform.position, Vector2.down * groundCheckDistance, Color.red);
        return hit.collider != null;
    }
}

额外配置说明

  1. 地面Layer设置:选中所有地面对象,在Inspector的Layer下拉框中选择"Add Layer",添加"Ground"层,然后给地面对象分配该层
  2. 参数调整:在Inspector面板中给groundCheckDistance设置一个略大于角色中心到地面的距离(比如0.6f,根据你的角色大小调整),speed和jumpPower保持原来的数值即可
  3. 跳跃优化:用Input.GetKeyDown替代Input.GetKey,这样按一次空格只跳一次,不会按住空格持续上升

内容的提问来源于stack exchange,提问作者William Sault

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:52:45