Move in another object's forward direction
Hello,
I have 2 objects. I would like to move object1 in the direction of object2's "forward" using object1.AddRelativeForce.
How can I get that direction vector?
Get the other object's transform. You can then just call something like
otherTransform.forward
to get the direction you want.
But that will move object1 in object2's forward direction relative to object1's forward. which is quite different than what i want.
I want object1 to move forward as if it was object2.
What do you mean by "relative to object1's forward"? The transform orientations are absolute.
The issue seems to be your use of AddRelativeForce vs just AddForce.
This does what you want:
// Rigidbodies we'll be assigning in the inspector
//
public Rigidbody body1;
public Rigidbody body2;
void Update()
{
// You shouldn't be doing physics operations here, but we'll make
// an exception.
//
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
{
// Get the 2nd object's forward
Vector3 otherForward = body2.transform.forward;
// Then push objectA along that direction
body1.AddForce(otherForward * 5, Force$$anonymous$$ode.Impulse);
}
}
That's not working for me. Please see attached image.
Helicopter = object1 The axis system you see on the helicopter = object2 (invisible dummy object)
I am keeping object2's y & z rotation the same as object1, and x axis is always 0. I want the helicopter to go forward according to object2. ins$$anonymous$$d it's going forward & down. because it's forward is down when it's angled down like in my image.
And this is my code: (i also tried your way before.)
if (forwardValue != 0)
{
dummyObject2.transform.rotation = Quaternion.Euler(new Vector3(0, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z));
dummyObject2.transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);
Vector3 direction = rb.transform.InverseTransformDirection(dummyObject2.transform.forward);
rb.AddRelativeForce(dummyObject2.transform.forward * 10000 * forwardValue);
}
As @TreyH already pointed out, you simply need to use AddForce, not AddRelativeForce. The rotation of the objects is then irrelevant.