- Home /
How to find the direction to translate an object, to move towards a point, regardless of rotation?
I have two objects. A and B. A moves around freely (A player.) B is an object which simply moves around based on a 'movement vector" , that is, a "horizontal" and "vertical" vector (NOT one fed in by the keyboard).
So, naturally, that "movement vector" is relative to B's rotation (i.e, "(0 , 1)" will move it forward)
I need to calculate that "movement vector" based on a "destination node" (which is calculated by a timer). I could just say "look at the node, and move forward" But, I need B to move towards the node even if its transform.forward changes.
I thought I just needed to multiply a direction vector by transform.forward of B. But I'm dumb! Thanks in advance for any help.
If you know the destination and where you're starting from, you can do this with basic vector math.
// Where you're starting
Vector3 source = new Vector3(0, -10, 20);
// Where you're going
Vector3 destination = new Vector3(10, 20, -5);
// Difference vector
Vector3 delta = (destination - source);
// Direction and distance
Vector3 sourceToDestination = delta.normalized;
float distance = delta.magnitude;
Answer by Hellium · Oct 02, 2018 at 03:36 PM
The following function will give you the direction vector in the local space of the given transform.
Vector3 GetLocalDirection( Transform transform, Vector3 destination )
{
return transform.InverseTransformDirection( (destination - transform.position).normalized );
}
You can use it as follow:
gameObjectB.transform.Translate( GetLocalDirection( gameObjectB.transform, destinationNode.transform.position ) ) ;
Your answer
Follow this Question
Related Questions
EnemyHover Script Error? 0 Answers
"Fake" Vector3.forward? 3 Answers
Unity2D, How do i check which way a sprite is facing? 1 Answer
Enemy moving left towards player. 1 Answer