Unity C#开发:如何实现类似Terraria的带加速减速的角色移动?
角色移动脚本修改方案与参数配置建议
一、修改后的带加速/减速与最大速度限制的PlayerMovement脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { private Rigidbody2D rb; private SpriteRenderer sprite; private Animator anim; private float dirX = 0f; // 移动相关参数:用[SerializeField]让编辑器可编辑 [SerializeField] private float acceleration = 5f; // 加速时的加速度 [SerializeField] private float deceleration = 8f; // 松开按键后的减速度 [SerializeField] private float maxMoveSpeed = 4f; // 最大移动速度 [SerializeField] private float jumpSpeed = 4f; // 跳跃速度 private void Start() { rb = GetComponent<Rigidbody2D>(); sprite = GetComponent<SpriteRenderer>(); anim = GetComponent<Animator>(); } private void Update() { dirX = Input.GetAxisRaw("Horizontal"); // 处理加速/减速与最大速度限制 float targetSpeed = dirX * maxMoveSpeed; // 计算当前速度与目标速度的差值 float speedDifference = targetSpeed - rb.velocity.x; // 根据是否有输入选择加速度/减速度 float accelerationRate = Mathf.Abs(targetSpeed) > 0.01f ? acceleration : deceleration; // 计算帧内速度变化量(乘Time.deltaTime保证帧率无关) float movement = speedDifference * accelerationRate * Time.deltaTime; // 应用速度变化 rb.velocity = new Vector2(rb.velocity.x + movement, rb.velocity.y); // 跳跃逻辑保留 if (Input.GetKeyDown(KeyCode.Space)) { rb.velocity = new Vector2(rb.velocity.x, jumpSpeed); } UpdateAnimation(); } // 更新角色动画 private void UpdateAnimation() { // 根据当前水平速度判断是否播放跑步动画(更贴合加速过程) bool isMoving = Mathf.Abs(rb.velocity.x) > 0.1f; anim.SetBool("running", isMoving); // 翻转 sprite 处理方向 if (dirX > 0f) { sprite.flipX = false; } else if (dirX < 0f) { sprite.flipX = true; } } }
二、移动参数配置方式建议
移动相关参数(如加速度、最大速度、跳跃速度)优先在Unity编辑器内修改,理由如下:
- 调试效率更高:无需重新编译代码,调整数值后可立即在场景中测试手感
- 协作更顺畅:策划、美术等非开发人员也能直接调整数值,适配游戏体验
- 代码安全性:用
[SerializeField]修饰变量,既可以在编辑器编辑,又不会被其他脚本意外修改 - 只有固定的逻辑阈值(如判断是否移动的0.1f)适合直接写在脚本中
内容的提问来源于stack exchange,提问作者Solaris
相关产品推荐
相关产品推荐

