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  );
}
}


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.
Vector3 forceDir = newPosition - transform.position;