How to sort array of tiles by direction character faces

Started by
1 comment, last by Mythix 10 years, 10 months ago

In a 2D grid, I have the center location of all tiles on the map in an array. I also have the character's facing ray (the starting position is the player's position). The character can rotate 360 degrees.

My goal would be to sort the array by the distance they are to that ray in a sweeping motion from the character's position outwards.

If you had two second hands on a clock set to noon, one going clockwise and the other going counter clockwise, the array would be:

12, 1, 11, 2, 10, 3, 9, 4, 8, 5, 7, 6

The only difference between that and what I'm hoping for is to do it on a 2D grid of tiles rather than just the numbers on a clock :P. Well, that and I'd hope if the lines intersect multiple tiles that I could add those tiles to the array based on their distance to the player.

Can someone point me in the right direction for this, perhaps even a term to describe the concept? If I'm not describing it well enough, please let me know and I'll do my best to draw a picture.

Advertisement

Use vectors. Have your direction vector as (xdir, ydir) and the vector from character to the tile as (tilex - playerx, tiley - playery).

To sort only on angle (ignoring distance)

normalise both vectors. Sort based on the dot product between the 2 normalised vectors. Highest dot product appears first in the list (dot product 1 => tile is dead ahead)

To sort on angle and distance:

as above, but if you get a tie in the dot product value, sort based on the normalised direction dotted with the unnormalised (tilex - playerx, tiley - playery). Lower dot product values appear earlier this time. If you want to include perpendicular tiles too (dot product is zero), that won't sort based on distance and you will need to actually calculate the magnitude squared of the distance from the player to the tile and sort based on that instead.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

@Paradigm Shifter

Thank you. That's exactly what I wanted and it's working great.

This topic is closed to new replies.

Advertisement