How to make gun shoot and aim towards the mouse

What I currently have. I have tried and in the game im working on, I want the players gun model to aim towards the mouse and I was wondering how I would have a gun or have the empty gameObject that the gun is on rotate towards the gun

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

public class gunShooting : MonoBehaviour
{

public Transform Bullet;
public Transform MuzzleFlash;
public Transform Spawn;
public AudioSource Shot;
public AudioSource noAmmo;
public Transform muzzleSpawn;
public Animation reload;

//Gun Stuff
public int bulletsPerMag = 30;
public int usingBulletPerMag;
public int overallAmmo;
public UnityEngine.UI.Text ammoDisplay;
public UnityEngine.UI.Text gunDisplay;

void Start()
{
    usingBulletPerMag = bulletsPerMag;
}
void Update()
{
    ammoDisplay.text = usingBulletPerMag + "/" + overallAmmo;
    if (overallAmmo > 0)
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            //overallAmmo -= bulletsPerMag - usingBulletPerMag;
            usingBulletPerMag = bulletsPerMag;
        }
    }
    if (Input.GetMouseButtonDown(0))
    {
        if (usingBulletPerMag > 0)
        {
            Shoot();
        }
        else
        {
            noAmmo.Play();
        }
    }
}
void Shoot()
{
    //Creating the bullet and shooting it
    var pel = Instantiate(Bullet, Spawn.position, Spawn.rotation);
    pel.GetComponent<Rigidbody2D>().AddForce(transform.right * 8000f);
    //Playing the bullet noise
    Shot.Play();

    //shooting and reloading
    usingBulletPerMag -= 1;
}

}

void Shoot()
{
Vector3 aimPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
aimPos.z = 0;

     //Creating the bullet and shooting it
     var pel = Instantiate(Bullet, Spawn.position, Spawn.rotation);
     pel.GetComponent<Rigidbody2D>().AddForce(aimPos.normalized * 8000f);
     //Playing the bullet noise
     Shot.Play();
     //shooting and reloading
     usingBulletPerMag -= 1;
}
  • SceenToWorldPoint will give you the exact location of the mouse in world space.

  • We keep the Z axis on 0 so it only keeps track of the X and Y axis.

  • When normalized, a vector keeps the same direction but its length is 1.0.

Haven’t tested this but I’m pretty sure you will figure it out.