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

Unity新手:如何用GetAxisRaw实现2D平台角色稳定移动

平台跳跃游戏角色移动脚本修改方案

我正在制作一款需躲避尖刺的平台跳跃游戏,此前尝试用transform.position方法实现角色移动但bug频发;使用Rigidbody2D的AddForce方法又存在加速度问题。了解到可通过GetAxisRaw实现移动,请问能否在现有脚本基础上修改,保留WASD与方向键控制的同时实现该功能?

修改后的完整脚本

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

public class PlayerScript : MonoBehaviour
{
    public float moveSpeed = 5f;
    public Rigidbody2D rb;
    public bool isGrounded = true;
    public float jumpForce = 7f;
    public float level = 1;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void FixedUpdate()
    {
        // 获取水平输入,自动兼容WASD与方向键
        float horizontalInput = Input.GetAxisRaw("Horizontal");
        
        // 直接设置水平速度,避免加速度累积问题
        rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);

        // 跳跃逻辑:仅在地面时触发
        if ((Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) && isGrounded)
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            isGrounded = false;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("enemy"))
        {
            Debug.Log("碰到敌人");
            if (level == 1)
            {
                Debug.Log("重置位置");
                transform.position = new Vector3(-11.343f, -0.49f, 0f);
            }
        }
        // 补充地面碰撞的进入检测,避免Stay检测的延迟
        else if (collision.gameObject.CompareTag("ground"))
        {
            isGrounded = true;
        }
    }

    private void OnCollisionStay2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("ground"))
        {
            isGrounded = true;
        }
    }
}

核心修改说明

  • 输入检测优化:用Input.GetAxisRaw("Horizontal")统一获取水平输入,Unity输入系统会自动映射WASD和方向键,无需单独判断每个按键,代码更简洁
  • 移动逻辑重构:直接设置Rigidbody2D.velocity的水平分量,替代AddForce,彻底解决加速度累积导致的移动失控问题,角色移动会立刻达到设定速度,手感更精准
  • 参数调整:原movespeed数值0.01过小,调整为5(可根据游戏手感微调);jumpheight改为jumpForce并调整为7,用velocity控制跳跃更直观
  • 碰撞检测优化:在OnCollisionEnter2D中补充地面检测,避免仅用OnCollisionStay2D可能出现的落地判定延迟问题
  • 代码规范:调整变量名符合驼峰命名法,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 18:54:24