How can I make a bullet face the position at which its being fired?

Hi, Im trying to make a bullet that goes to the position where the mouse is at the moment the player fires. I manage to write a code that does exactly that, the only problem is that the bullet is always facing north, making it look ugly when the player fires the gun. Can you help me to find a way of making the bullet rotate to the place the player is shooting at?

public class MachineGun: MonoBehaviour
{
    public Transform firepoint;
    public GameObject bullet;
    public GameObject bullet1;

    int ammo = 100;
    float nextTimeToFire = 0f;
    bool shoot;

    Vector3 mousePos;
    public static Vector2 direction;

void Update()
 {
        //Aiming.
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        direction = (Vector2)((mousePos - firepoint.position));
        direction.Normalize();

        //Shooting.
        if (Input.GetKey(KeyCode.Mouse0) && ammo > 1)
    {
        if(nextTimeToFire <= 0.04f)
        {
            nextTimeToFire += Time.deltaTime;
            if(!shoot)
            {
                Shooting();
                shoot = true;
            }  
        }
        else
        {
            shoot  = false;
            nextTimeToFire = 0f;
        }
    }
    else
    {
        shoot= false;
        nextTimeToFire = 0f;
    }
}


    void Shooting()
    {
        bullet1 = Instantiate(bullet, firepoint.position, Quaternion.Euler(Vector3.forward));
        ammo -= 1;
    }

(Im sorry for any grammar error, English is not my first language)

1 Answer

1

Instantiate(bulletPrefab, directionObject.transform.position, Quaternion.LookRotation(directionObject.transform.forward));

Use the local rotations not the global ones.

Each objects have diffarent forward rotations based on their pivots etc.

I hope it will make sense.

Yeah you´re right, thanks for helping me!