RigidBody object AddForce does not go in direction of mouseclick

I am trying to make a ball go in the direction of a mouseclick, but wherever i click, the ball does not go in the same direction as the mouse click.

Here is the code I am using:

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

public class NewMouse : MonoBehaviour {

       public Rigidbody2D rb;
       public Vector2 buttonDown;

	// Use this for initialization
	void Start () {
	    rb = GetComponent<Rigidbody2D>();
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetMouseButtonDown(0)) {

		    buttonDown = Input.mousePosition;
		    Debug.Log("Button: " + buttonDown);

		    rb.AddForce(buttonDown - rb.position);
		    }
	}
}

However, even if i click in the bottom left of the screen, the ball zooms off in another direction. How do i make it go to the exact spot i want it?

Try to ready the documentation for Input.mousePosition first. You’ll soon discover that the mouse returns coordinates in screenspace i.e. pixel coordinates of the screen.

Pretty much everything else in the world uses world coordinates and not screen coordinates which are just a representation of your view on the world.

To convert from screen coordinates to world coordinates you need to ask a specific camera to turn the position on the screen into a world coordinate i.e. something it’s looking at. With only a single camera you typically use Camera.main.

So using the selected camera you can call Camera.ScreenToWorldPoint. Note however that this function requires a Vector3 whereas a mouse position is a Vector2. This is because you need to effectively specify how far away from the camera you want. When using orthographic mode, this has no real impact but if you’re using perspective mode then it is important you specify it.

This leads to something like the following:

   var mousePos = Input.mousePosition;
   mousePos.z = 0; // We want zero units from the camera but we can specify whatever we want here.
   Debug.Log (Camera.main.ScreenToWorldPoint (mousePos));

Note that you’ll get a Vector3 back but you can ignore the Z position when dealing with 2D.

The next thing I should mention is that using the Rigidbody2D.AddForce will work but that method obviously requires a force and not a distance. It might prove difficult to get the balance correct if you’re trying to move the Rigidbody2D towards that position. You might want to consider adding a TargetJoint2D to the Rigidbody2D and set the TargetJoint2D.target property to the position you want it to move to. This will give you a stable movement and allow you to control the forces used to move it there i.e. control how fast and how quickly it converges to that position with little to no overshoot.

Hope this helps.