You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity C#脚本旋转偏移问题:多角度发射子弹异常求助

问题分析

你的脚本问题出在依赖子弹Transform的旋转来计算发射方向,Space.Self的旋转是基于子弹自身当前的局部坐标系。如果子弹预制体初始旋转未和firePoint完全对齐,或者实例化时旋转传递出现偏差,就会导致tr.up方向错误,出现子弹直射的情况。

修复方案

直接计算偏移角度后的方向向量来施加力,不依赖子弹旋转状态,稳定性更强。优化后的代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour
{
    public Transform firePoint;
    public GameObject BulletPrefab;
    
    public float bulletSpeed = 20f;
    private readonly float[] fireAngles = {-15f, 0f, 15f};
    
    void Update()
    {
        if(Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }
    
    void Shoot()
    {
        foreach (var angle in fireAngles)
        {
            // 计算偏移后的发射方向
            Vector2 direction = Quaternion.Euler(0, 0, angle) * firePoint.up;
            
            // 实例化时直接设置正确旋转,确保子弹视觉朝向和发射方向一致
            GameObject bullet = Instantiate(BulletPrefab, firePoint.position, firePoint.rotation * Quaternion.Euler(0,0,angle));
            
            Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
            rb.AddForce(direction * bulletSpeed, ForceMode2D.Impulse);
        }   
    }
}
关键改进点
  • 直接计算方向向量:通过Quaternion.Euler(0,0,angle) * firePoint.up生成偏移方向,完全规避子弹预制体初始旋转带来的干扰。
  • 简化代码逻辑:用foreach替代while循环,代码更简洁易读。
  • 规范变量命名:将Speed改为bulletSpeed、b1改为fireAngles,提升代码可维护性。
  • 统一旋转设置:实例化时直接把偏移角度应用到旋转参数,确保视觉与运动方向一致。
额外建议
  • 确认子弹预制体的Rigidbody2D重力缩放设为0,避免重力干扰飞行轨迹。
  • 可将fireAngles设为public,直接在Inspector面板调整偏移角度,无需修改代码。

内容的提问来源于stack exchange,提问作者pankeczap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:20:39