Rigidbody2d.addforce in the direction of mouse problem

I’m currently using this code to addforce in the direction of the mouse:

mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseDir = mousePos - gameObject.transform.position;
mouseDir = mouseDir.normalized;

		if (Input.GetMouseButtonDown(0)) {
			rb.AddForce(mouseDir * 1500);
		}

It works fine however, the problem is that the force applied changes depending on how far my mouse is from the object. Is there any other way to do it so that the force is not affected by the distance from the mouse?

First, I would ensure that you’re not doing this in anything other than the FixedUpdate callback otherwise it’ll be dependent upon the frame-rate. Second, you’re using Vector3 and not Vector2 which Unity is implicitly converting for you however in this case, it’s causing a problem as you’re getting Z in your ‘mouseDir’.

I would reset the Z like so:

void FixedUpdate ()
{
	var mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
	var mouseDir = mousePos - gameObject.transform.position;
	mouseDir.z = 0.0f;
	mouseDir = mouseDir.normalized;

    if (Input.GetMouseButtonDown(0))
	{
         rb.AddForce(mouseDir * 1);
    }
}

… before normalizing to remove any Z difference (assuming you’re not using a 3D mouse).

With this change, it will always produce a unit-normal in the direction of the mouse as you desire and ignore any Z differences. In the very least, it’ll remove Z from the normalized components. If you’re seeing anything else then something else is going wrong.