- Home /
Angle Between Points
I am making a top-down field-of-view system similar to Monaco. I've managed to assemble a list of all the corners of walls visible from the player's position (as Vector3s), and I need to sort them in a clockwise order around the player. I've already tried to implement a solution using Vector3.Angle and this, but it isn't working and returns largely nonsensical angles. How might I go about sorting these points?
Answer by robertbu · Mar 14, 2014 at 03:41 AM
I believe you only need the angles on a single plane (i.e. you are not looking for angles in 3D space. If so, you can use Mathf.Atan2(). I cannot tell from your description if you game is played on the XY plane or the XZ plane. I also cannot tell what side of your character is considered forward. So let's say that it is played on the XY plane and you consider the right side of the character as forward. To start with you can get a base angle from the forward of the character. Then for all the objects you can get a normalzied angle relative to the character.
var dir = transform.right;
var charAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Then for each object you can do something like:
dir = obj.position - transform.position;
var objAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - charAngle;
if (objAngle < 0.0) objAngle += 360.0;
The result will be an angle relative to the player that grows counterclockwise. For a clockwise rotation, simply sort the angles in descending order. Note for your purposes you don't need to convert from radians to degrees. You can leave off the Mathf.Rad2Deg and just add Mathf.PI * 2 for negative angles.
Your answer
Follow this Question
Related Questions
2D: Transparency Sort Axis not properly affecting Tilemaps? 2 Answers
How to create a field of view for enemy ai that detects a player Unity 2d? 3 Answers
Proper/Standard way to create a top down / isometric sprite sorting solution 1 Answer
CustomAxis sort not working between objects placed at different layers rendered by multiple cameras 0 Answers
Camera FOV lower than 1? 1 Answer