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

Unity 2D平台角色移动跳跃异常:松键仍移动且无法跳移

问题修复方案

问题根源

  1. 松开方向键仍移动:使用Input.GetKeyDown仅在按键按下瞬间触发一次,直接设置velocity为纯水平方向后,未在松开时重置水平速度,刚体因物理惯性持续移动。
  2. 跳跃时无法左右移动:跳跃代码直接将velocity设为Vector2.up * JumpStrength,覆盖了水平方向速度;左右移动代码同理覆盖垂直方向速度,导致两个动作互斥。

修复后的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public Rigidbody2D myRigidbody;
    public float JumpStrength = 8f;
    public float Speed = 5f;
    // 可选:地面检测(需在角色脚下添加空物体作为检测点)
    public Transform groundCheck;
    public float groundCheckRadius = 0.2f;
    public LayerMask groundLayer;
    private bool isGrounded;

    void Update()
    {
        // 检测角色是否在地面,防止无限跳跃
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, groundLayer);

        // 跳跃逻辑:保留水平速度,仅修改垂直速度
        if (Input.GetKeyDown(KeyCode.UpArrow) && isGrounded)
        {
            myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, JumpStrength);
        }

        // 移动逻辑:获取连续水平输入,保留垂直速度
        float horizontalInput = Input.GetAxis("Horizontal");
        myRigidbody.velocity = new Vector2(horizontalInput * Speed, myRigidbody.velocity.y);
    }
}

关键修改说明

  • 移动逻辑:
    • 改用Input.GetAxis("Horizontal"),它会返回-1(左)到1(右)的连续值,松开按键时自动归0,自然停止移动。
    • 设置velocity时保留myRigidbody.velocity.y,确保跳跃时的垂直速度不被覆盖,实现空中移动。
  • 跳跃逻辑:
    • 设置velocity时保留myRigidbody.velocity.x,确保跳跃时的水平速度不丢失。
    • 新增地面检测(可选但推荐),避免角色在空中反复跳跃。若不需要可删除isGrounded相关代码,但建议保留以符合平台游戏常规逻辑。

手感优化提示

若觉得GetAxis输入太灵敏,可在Unity编辑器的Edit > Project Settings > Input Manager中调整Horizontal轴的Gravity和Sensitivity参数,适配操作手感。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:37:09