Shooting at the player in 3D space

Hi guys

This code shoots at the player in a 2D space, but i just cant get it working in 3D.
It seems to just always shoot left no matter where the player is.

This line
newBullet.GetComponent().AddRelativeForce(new Vector2(0f, torpedoSpeed));

used to be

newBullet.GetComponent().AddRelativeForce(new Vector2(0f, torpedoSpeed));

but it didnt make any difference.

lastTimeShot = Time.time;
                float angle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg - 90f;
                Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
                GameObject newBullet = Instantiate(roundUFOTorpedo, transform.position, q);
                newBullet.GetComponent<Rigidbody>().AddRelativeForce(new Vector2(0f, torpedoSpeed));
                lastTimeShot = Time.time;
                Destroy(newBullet, 5);

You probably want to use Vector3 here or something. That Vector2 means torpedoSpeed long vector to the left. So it will always push the newBullet to the left.

Hello. Thinking that it could be the same for Vector2 and Vector3, respectfully you are totally wrong. Vector3 means that you have a third dimension and you HAVE to use a Rigidbody (not a Rigidbody2D). If you want to shot a bullet forward, you should create a script more or less similar with this one. I guess that you want to apply a force on your bullet rigidbody (of course, your instantiated bullet must have a Rigidbody component). Code tested :

using UnityEngine;
// instantiate a rigidbody then set its velocity
public class BulletBehavior : MonoBehaviour
{   // assign a Rigidbody component in the inspector to instantiate
    public Rigidbody projectile;
    public float force = 10f;

    void Update()
    {   // left mouse button pressed
        if (Input.GetMouseButtonDown(0))
        {   // instantiate the projectile
            Rigidbody clone;
            clone = Instantiate(projectile, transform.position + transform.forward * 0.5f, transform.rotation);
            // give the cloned object an initial velocity
            clone.velocity = transform.TransformDirection(Vector3.forward * force);
            Destroy(clone.gameObject, 2); // destroy bullet after 2 seconds
        }
    }
}