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

Unity 2D游戏新手求适配2D物理的简易移动脚本(含Time.fixedDeltaTime)

适配2D物理的简易移动脚本(保留Time.fixedDeltaTime)

我是Unity引擎的新手,正在开发一款2D游戏。使用2D effector时,直接修改transform.position的移动脚本会导致角色出现异常行为,更换脚本后问题解决,但新脚本存在诸多问题。最初使用的脚本如下:

horizontal = Input.GetAxis("Horizontal");
transform.position += new Vector3(horizontal, 0, 0) * Time.fixedDeltaTime * speed; 

现需要一款适配2D物理的简易移动脚本,且必须保留Time.fixedDeltaTime——我的硬件性能较弱,缺少它游戏运行会很卡顿。


解决方案脚本

直接修改transform.position会绕过Unity的2D物理系统,和2D effector这类物理交互组件冲突,所以应该通过Rigidbody2D来控制移动。以下是符合要求的脚本:

using UnityEngine;

public class Player2DMovement : MonoBehaviour
{
    [SerializeField] private float moveSpeed = 5f;
    private Rigidbody2D rb;
    private float horizontalInput;

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

    private void Update()
    {
        // 在Update中获取输入,保证响应及时
        horizontalInput = Input.GetAxis("Horizontal");
    }

    private void FixedUpdate()
    {
        // 物理操作放在FixedUpdate中,天然基于Time.fixedDeltaTime更新
        Vector2 moveVelocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);
        rb.velocity = moveVelocity;
    }
}

核心说明

  • 依赖Rigidbody2D控制移动,让角色和2D effector等物理组件正常交互,彻底解决异常行为
  • 输入逻辑放在Update,物理移动放在FixedUpdate,符合Unity的更新周期规范
  • FixedUpdate的执行频率由Time.fixedDeltaTime控制,完全满足你对硬件性能适配的需求,不会出现卡顿
  • 保留Input.GetAxis的平滑输入效果,若需要更灵敏的响应,可替换为Input.GetAxisRaw

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 07:47:02