Unity 2D玩家朝向发射子弹异常:子弹仅向上飞行的解决问询
问题解决:子弹无法沿玩家朝向发射
问题根源
- 生成子弹时未继承发射点(或玩家)的旋转角度,使用
Quaternion.identity强制子弹保持默认朝向(向上)。 - 子弹移动逻辑固定使用全局
Vector3.up,未根据自身朝向调整移动方向。
修改方案
1. 修正Player脚本的子弹生成逻辑
在生成子弹时,传入发射点的旋转角度,确保子弹初始朝向与玩家一致:
if (Input.GetKeyDown(KeyCode.Space)) { // 使用bulletPoint的旋转代替Quaternion.identity Instantiate(_bulletPrefab, _bulletPoint.transform.position, _bulletPoint.transform.rotation); }
2. 修正Bullet脚本的移动逻辑
让子弹沿自身的up方向移动(玩家的旋转绕Z轴,up方向即为当前朝向):
void Update() { // 替换全局Vector3.up为transform.up,沿自身朝向移动 transform.Translate(transform.up * _speed * Time.deltaTime); }
额外提示
Player脚本的CalculateMovement方法存在重复的transform.Translate调用,会导致实际移动速度翻倍,建议移除前两行单独的Translate代码,保留统一的移动逻辑:
void CalculateMovement () { float horizontalInput = Input.GetAxis("Horizontal"); float verticalInput = Input.GetAxis("Vertical"); Vector2 movementDirection = new Vector2(horizontalInput, verticalInput); float inputMagnitude = Mathf.Clamp01(movementDirection.magnitude); movementDirection.Normalize(); // 仅保留这一行移动逻辑即可 transform.Translate(movementDirection * _speed * inputMagnitude * Time.deltaTime, Space.World); if (movementDirection != Vector2.zero) { Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, movementDirection); transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime); } }
内容的提问来源于stack exchange,提问作者Umer Ansari
相关产品推荐
相关产品推荐

