Wrong Rotation When Instantiating Bullet

I am trying to make an FPS. But, when I shoot, the bullet is facing the wrong way. It is shooting along the raycast line. But that’s really it. It’s not facing forward, instead, facing sideways. I have attached an image.

Here is the main code.

using UnityEngine;

public class PlayerShooting : MonoBehaviour
{
    public GameObject bulletPrefab;
    public Transform bulletSpawn;
    public float bulletSpeed = 20f;
    public float cooldownTime = 1f;


    private float lastShootTime = 0f;

    void Update()
    {
        if (Input.GetMouseButtonDown(0) && Time.time >= lastShootTime + cooldownTime)
        {
            Shoot();
            lastShootTime = Time.time;
        }
    }

    void Shoot()
    {
        RaycastHit hit;
        Vector3 shootDirection;

        if (Physics.Raycast(bulletSpawn.position, bulletSpawn.forward, out hit))
        {
            shootDirection = (hit.point - bulletSpawn.position).normalized;
        }
        else
        {
            shootDirection = bulletSpawn.forward;
        }

        GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, Quaternion.identity);

        bullet.transform.rotation = Quaternion.LookRotation(shootDirection);

        BulletMovement bulletMovement = bullet.GetComponent<BulletMovement>();
        if (bulletMovement != null)
        {
            bulletMovement.Initialize(shootDirection);
            bulletMovement.speed = bulletSpeed;
        }
    }

    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawRay(bulletSpawn.position, bulletSpawn.forward * 100);
    }
}

Right here is the code for my attempt at fixing said issue.

using UnityEngine;

public class BulletMovement : MonoBehaviour
{
    public float speed = 20f;
    private Vector3 direction;

    public void Initialize(Vector3 shootDirection)
    {
        direction = shootDirection.normalized;
    }

    void Update()
    {
        transform.position += direction * speed * Time.deltaTime;
    }
}

Either your bulletSpawn transform isn’t pointing in the correct direction or the bullet’s model isn’t orientated along the forward/blue axis. You can fix the mesh’s orientation in a modeling application like Blender.

BTW - your gun is shooting bullets with the casing still attached. :slight_smile:

Thank you! I will try this. Thank you for reminding me about the casing lol

I fixed the error.