- Home /
Question by
Blanketsniffer · Apr 15, 2019 at 05:17 PM ·
physicsrigidbody
AddRelativeForce() does not add the force relatively
I have want to add force to a Rigidbody by dragging mouse on the screen. even though I have transformed screen coordinates to the world coordinates and rotation of the Rigidbody looks at the coordinates where the mouse button is released, When I add relative force by AddRelativeForce ball goes directly forward.
public GameObject ballPrefab;
GameObject ballInstance;
private float force=15;
Vector3 mouseStart;
Vector3 mouseStop;
float minDragDistance=15f;
float zDepth=20f;
void FixedUpdate()
{
if (Input.GetMouseButtonDown(0))
{
mouseStart = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0))
{
mouseStop = Input.mousePosition;
if(Vector3.Distance(mouseStop, mouseStart) > minDragDistance)
{
//Here I am getting the position on screen coordinates to throw the rigidbody to
Vector3 hitPos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, zDepth);
//I transform screen coordinates to world coordinates
Vector3 hitPoss = Camera.main.ScreenToWorldPoint(hitPos);
//transforming rigidbody to look at hitpos direction
ballInstance.transform.LookAt(hitPoss);
//adding relative force to the rigidbody
ballInstance.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * force, ForceMode.Force);
}
}
}
As I commented in the code I change the transform.rotation properties of my game object with LookAt() function and when I check the inspector it changes the rotation just right. but by AddRelativeForce(Vector3.forward) it directly goes forward on global z direction instead of locally changed z direction.
Comment
Your answer