using UnityEngine;
///
/// 基于Unity Input Manager的3D对象前后左右移动脚本
///
public class PlayerMove3D : MonoBehaviour
{
[Header("移动配置")]
[Tooltip("移动速度(单位:米/秒)")]
public float moveSpeed = 5f;
[Tooltip("是否使用物理系统(Rigidbody)移动")]
public bool useRigidbody = true;
public bool player2;
// 3D物理组件引用
private Rigidbody rb;
// 初始化
private void Start()
{
// 如果启用物理移动,自动获取或添加Rigidbody组件
if (useRigidbody)
{
rb = GetComponent();
if (rb == null)
{
// 自动添加Rigidbody,并默认关闭重力(如果需要下落可开启)
rb = gameObject.AddComponent();
rb.useGravity = false;
rb.freezeRotation = true; // 冻结旋转,避免移动时对象倾倒
}
}
}
// 帧更新(物理移动推荐用FixedUpdate,非物理用Update)
private void Update()
{
if (!useRigidbody)
{
MoveByTransform();
}
}
// 物理帧更新(固定时间步长,默认0.02秒)
private void FixedUpdate()
{
if (useRigidbody)
{
MoveByRigidbody();
}
}
///
/// 方式1:直接修改Transform移动(无物理)
///
private void MoveByTransform()
{
// 1. 获取Input Manager的水平/垂直输入(返回值范围:-1 ~ 1)
float horizontalInput = player2 ?
(Input.GetKey(KeyCode.LeftArrow) ? -1 : 0) + (Input.GetKey(KeyCode.RightArrow) ? 1 : 0) :
(Input.GetKey(KeyCode.A) ? -1 : 0) + (Input.GetKey(KeyCode.D) ? 1 : 0);
float verticalInput = player2 ?
(Input.GetKey(KeyCode.DownArrow) ? -1 : 0) + (Input.GetKey(KeyCode.UpArrow) ? 1 : 0) :
(Input.GetKey(KeyCode.S) ? -1 : 0) + (Input.GetKey(KeyCode.W) ? 1 : 0);
// 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);
}
///
/// 方式2:通过Rigidbody移动(带物理,推荐)
///
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;
}
}