diff options
Diffstat (limited to 'Assets/Scripts/PlayerController.cs')
| -rw-r--r-- | Assets/Scripts/PlayerController.cs | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/Assets/Scripts/PlayerController.cs b/Assets/Scripts/PlayerController.cs new file mode 100644 index 0000000..10bde44 --- /dev/null +++ b/Assets/Scripts/PlayerController.cs @@ -0,0 +1,98 @@ +using UnityEngine; + +/// <summary> +/// 基于Unity Input Manager的3D对象前后左右移动脚本 +/// </summary> +public class PlayerMove3D : MonoBehaviour +{ + [Header("移动配置")] + [Tooltip("移动速度(单位:米/秒)")] + public float moveSpeed = 5f; + + [Tooltip("是否使用物理系统(Rigidbody)移动")] + public bool useRigidbody = true; + + // 3D物理组件引用 + private Rigidbody rb; + + // 初始化 + private void Start() + { + // 如果启用物理移动,自动获取或添加Rigidbody组件 + if (useRigidbody) + { + rb = GetComponent<Rigidbody>(); + if (rb == null) + { + // 自动添加Rigidbody,并默认关闭重力(如果需要下落可开启) + rb = gameObject.AddComponent<Rigidbody>(); + rb.useGravity = false; + rb.freezeRotation = true; // 冻结旋转,避免移动时对象倾倒 + } + } + } + + // 帧更新(物理移动推荐用FixedUpdate,非物理用Update) + private void Update() + { + if (!useRigidbody) + { + MoveByTransform(); + } + } + + // 物理帧更新(固定时间步长,默认0.02秒) + private void FixedUpdate() + { + if (useRigidbody) + { + MoveByRigidbody(); + } + } + + /// <summary> + /// 方式1:直接修改Transform移动(无物理) + /// </summary> + private void MoveByTransform() + { + // 1. 获取Input Manager的水平/垂直输入(返回值范围:-1 ~ 1) + float horizontalInput = Input.GetAxis("Horizontal"); // 左右:A/D 或 左/右方向键 + float verticalInput = Input.GetAxis("Vertical"); // 前后:W/S 或 上/下方向键 + + // 2. 构建移动方向向量(基于世界坐标系的X/Z平面,Y轴不变避免上下移动) + Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput); + + // 3. 归一化向量:解决斜向移动时(左右+前后同时输入)速度过快的问题 + if (moveDirection.magnitude > 1f) + { + moveDirection.Normalize(); + } + + // 4. 计算移动位移并更新对象位置 + transform.Translate(moveDirection * moveSpeed * Time.deltaTime, Space.World); + } + + /// <summary> + /// 方式2:通过Rigidbody移动(带物理,推荐) + /// </summary> + private void MoveByRigidbody() + { + // 1. 获取输入 + float horizontalInput = Input.GetAxis("Horizontal"); + float verticalInput = Input.GetAxis("Vertical"); + + // 2. 构建移动方向向量 + Vector3 moveDirection = new Vector3(horizontalInput, 0f, verticalInput); + + // 3. 归一化处理 + if (moveDirection.magnitude > 1f) + { + moveDirection.Normalize(); + } + + // 4. 设置Rigidbody的速度(实现平滑移动,受物理引擎约束) + rb.linearVelocity = moveDirection * moveSpeed; + } +} + + |
