TomP TomP - 9 months ago 40
C# Question

Applying force to sphere sends it in unpredictable directions

I am trying to move (fire) a sphere in the direction of a mouse click. But when I click, the sphere moves in unpredictable directions.

My code for adding the force to move the sphere:

if (Input.GetMouseButtonDown(0)){

RaycastHit hit;

* We r using raycasting to detect mouse click on plane
* */
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

if (Physics.Raycast(ray, out hit)){
newPosition = hit.point;
this.GetComponent<Rigidbody>().AddForce( (newPosition).normalized * 25, ForceMode.Impulse );

Answer Source

You've supplied an incorrect argument for Rigidbody.AddForce(). The vector you supply for the first argument should not be the position you want the force to point towards - it should be the direction of the force, multiplied by the magnitude.

In this case, you can calculate the direction of the force by subtracting the current position of the object from the target position:

Vector3 forceDir = newPosition - transform.position;
this.GetComponent<Rigidbody>().AddForce( forceDir.normalized * 25, ForceMode.Impulse  );

Hope this helps! Let me know if you have any questions.