Reputation: 663
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
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.
Upvotes: 0
Views: 3862
Reputation: 349
AddRelativeForce
applies a force relative to the parent object's orientation, which doesn't really make sense here, since there is no parent object.
Instead of:
ballInstance.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward * force, ForceMode.Force);
Try:
ballInstance.GetComponent<Rigidbody>().AddForce(ballInstance.transform.forward * force, ForceMode.Force);
This should work, since instead of using the global forward Vector Vector3.forward
, you are using the forward Vector of your ballInstance ballInstance.transform.forward
Upvotes: 1
Reputation: 27011
Changing the transform won't take effect instantly, you should set Rigidbody.rotation
instead.
Check the document: https://docs.unity3d.com/ScriptReference/Rigidbody-rotation.html
Upvotes: 0