子弹在 Unity 中向后发射?

Bullet firing backwards in Unity?

我正在使用 Unity 创建游戏,并且正在学习 C#。我在游戏的子弹发射机制方面需要一些帮助,因此我在 Unity Answers 上找到了以下脚本。它工作得很好,但向后发射子弹(这会使游戏中的任何人处于糟糕的境地)。有人能帮忙吗?谢谢!

using UnityEngine;
using System.Collections;

public class ShootDemo : MonoBehaviour
{
    public Rigidbody projectile;
    public float speed = 20;

    // Update is called once per frame
    void Update()
        {
        if (Input.GetButtonDown("Fire1"))
        {
            Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, 
transform.rotation) as Rigidbody;
            instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, speed));
        }
    }
}

如果 ShootDemo 的游戏对象的前向(蓝轴)指向您想要射击的方向,那么您所拥有的将会起作用。

事实上,它朝相反的方向射门意味着前锋指向的实际上是指向相反的方向。

通过否定速度来考虑这一点将反转速度以产生所需的效果:

instantiatedProjectile.velocity = transform.forward * -speed;

或您已经使用的格式

instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0, -speed));