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

Unity中C#射击脚本优化请求:实现随转向改变子弹轨迹

Unity射击脚本优化:让子弹随武器转向飞行

问题出在你使用了Vector3.forward——这是世界坐标系的固定Z轴方向,和武器自身的转向无关。要让子弹沿武器当前的朝向飞行,需要改用物体自身坐标系的前方向,也就是transform.forward。

修改后的代码如下:

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

public class ShotToClick : MonoBehaviour
{
    public GameObject Bullet;
    public float Power;
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject b = Instantiate(Bullet, transform.position, transform.rotation);
            // 改用transform.forward获取武器当前的前方向
            b.GetComponent<Rigidbody>().AddForce(transform.forward * Power, ForceMode.Impulse);
        }
    }  
}

额外优化建议:每次实例化子弹后调用GetComponent会有一定性能开销,你可以提前在子弹预制体上挂载Rigidbody并缓存引用,或者用TryGetComponent避免空引用报错:

if (b.TryGetComponent(out Rigidbody rb))
{
    rb.AddForce(transform.forward * Power, ForceMode.Impulse);
}

内容的提问来源于stack exchange,提问作者Mr. Bait

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:51:40