Unity 2D战舰战斗游戏:实现前后移动与旋转控制需求
2D战舰移动问题修复方案
你当前的移动逻辑核心问题是:移动方向始终绑定世界空间的Y轴,没有跟随战舰的旋转角度,所以战舰转向后仍会往固定方向移动,无法实现沿自身朝向前进/后退的效果。
核心修改点
- 将前后输入转换为战舰自身局部坐标系的方向,再映射到世界空间
- 简化输入处理逻辑,移除不必要的方向渐变逻辑,提升操控响应速度
修改后的完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { public float moveSpeed; public float smoothing; public float rotationSpeedL; public float rotationSpeedR; private Rigidbody2D rb; void Start() { rb = GetComponent<Rigidbody2D>(); } void FixedUpdate() { // 读取按键输入 bool inputU = Input.GetKey(KeyCode.W); bool inputD = Input.GetKey(KeyCode.S); bool inputL = Input.GetKey(KeyCode.A); bool inputR = Input.GetKey(KeyCode.D); // 执行旋转逻辑(保留原有正常运行的代码) if (inputL) { transform.Rotate(0, 0, rotationSpeedL); } if (inputR) { transform.Rotate(0, 0, rotationSpeedR); } // 计算移动输入值 float moveInput = 0; if (inputU) moveInput = 1; else if (inputD) moveInput = -1; // 将战舰局部前后方向转换为世界空间向量(2D场景中transform.up对应战舰朝前方向) Vector2 moveDir = transform.up * moveInput; // 平滑设置刚体速度 rb.velocity = Vector2.Lerp(rb.velocity, moveDir * moveSpeed, smoothing); } }
关键说明
- 方向适配:
transform.up代表战舰自身坐标系的向上方向(即模型朝前的方向),乘以输入的±1后,就能得到战舰当前朝向的前进/后退向量。如果你的战舰模型默认朝前方向是transform.right,直接替换即可。 - 输入优化:用互斥判断直接设置移动输入值,避免原代码中方向渐变的逻辑,消除移动响应延迟,更符合战舰操控的硬朗手感。
内容的提问来源于stack exchange,提问作者porglord27 yt
相关产品推荐
相关产品推荐

