Need help Instantiating a projectile and adding a force to it, from player position,towards mouse position

public Transform gun;
public Rigidbody bullet;
void Update()
{
if (Input.GetMouseButtonDown(0))
Fire();
}

void Fire()
{
    Vector3 mousePosit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    //mousePosit.y = 19;
    Rigidbody firedProj;
    firedProj = Instantiate(bullet, gun.position, gun.rotation);
    firedProj.AddForce(mousePosit.normalized * 5000);
}

This is the code I am using currently.The outcome of this is that the projectiles are shot towards the camera position not the mouse position.I am using an RTS bird view camera which you can move by scrolling to the edges with your mouse. So I don’t understand why I don’t get the mouse position in world space.

@dspirelja Hi there, and welcome to Unity answers!

This seems to be a bit of a strange way of achieving what you want - why not just make the gun look at the target by using Transform.LookAt() then applying force to the new bullet along one axis? Specifically, the axis now pointing at the object?

Documentation:

Example:

 void Fire()
 {
     Vector3 mousePosit = Camera.main.ScreenToWorldPoint(Input.mousePosition);
     gun.LookAt(mousePosit);
     Vector3 forceToAdd = new Vector3(0f, 0f, 0f); //change these values to whatever you need to make the bullet move along one specific axis
     GameObject firedProj;
     firedProj = Instantiate(bullet, gun.position, gun.rotation) as GameObject;
     firedProj.GetComponent<Rigidbody>().AddForce(forceToAdd);
 }

please note this will only apply the force once, so if you need to apply the force consistently you will need to adjust the code to do that.

Hope this helps!