- Home /
Position in relation to another object
My game uses 2D enemies in 3D space. The enemies graphics are obviously flat and are always facing the player. However, I want a different graphic to be displayed for each enemy based on a variable facingDirection which has an enum value corresponding to 8 compass points (N, NE, E, SE, S, etc.) as well as the player's position in relation to the enemy.
To be more clear: If the enemy is facing north, and the player is standing to the north of the enemy, I want the enemy's graphic to display its front. If the enemy is facing north and the player is standing to the south of the enemy, I want the player to see its back.
I have an algorithm to calculate this, but it's somewhat complex and I don't want to waste time implementing it if there is a built-in function within Unity.
My question is: Is there such a function in Unity (To find one gameobject's position in relation to another)?
Any help is appreciated.
$$anonymous$$aybe using an animator and changing its states would suffice?
Yes. But I would still need to know the player's position in relation to the enemy in order to deter$$anonymous$$e which state to use.
Perhaps I misunderstand, but this sounds like a simple Vector3 subtraction operation to me.
You can "Normalize" the result to get a vector of magntiude 1, a "direction".
if you want an angle as the result (the Atan2 operation does NOT need normalization)...
Subtraction was part of my algorithm, but I was working with x and y individually. Didn't realize there was an operator for subtracting vectors. I think I can make use of Atan2 as well. If you want to convert this to an answer, I would be happy to accept it.
Thanks, Jake
You can perform $$anonymous$$ANY operations with vectors: you can add & subtract two vectors, you can multiply or divide (scale) a vector by a float, and then there are the CrossProduct and DotProducts which while not technically "multiply" operations, are kind of like two different ways of multiplying two vectors (but wiki them for details).
Answer by Glurth · Jan 25, 2015 at 04:51 PM
To find one gameobject's position in relation to another
Perhaps I misunderstand, but this sounds like a simple Vector3 subtraction operation to me.
Vector3 player_relative_to_enemy=enemy.transform.position - player.transform.position;
You can "Normalize" the result to get a vector of magntiude 1, a "direction".
player_relative_to_enemy.Normalize();
if you want an angle as the result (the Atan2 operation does NOT need normalization)...
float angle=Mathf.Atan2(player_relative_to_enemy.x,player_relative_to_enemy.y);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Detect exactly where other objects around player are 3 Answers
Distribute terrain in zones 3 Answers
How to set to game objects's position from 2 different game objects arrays equal to each other? 0 Answers
Why is the camera going crazy when the player moves? 0 Answers