简体   繁体   中英

Finding the distance between two objects in a 2D array, not going Diagonal

Not sure if this was posted before, but this is a relatively short question

I am currently working on a maze game being chased by something.

Currently, the player starts at (0,0), and the monster starts at (9,9). If moving is incrementing/decrementing one (not both), what is the algorithm/code to find the amount of moves it'd take for the monster to reach the main character?

From the comments I realized I should have clarified a few thing.

If the room type is 1, then it's a wall, else is open. But the main thing is that the walls do NOT impact the monster. Perhaps the better way to ask is how many moves would it take if all of the arrays were open.

You could take a look at the A* search algorithm which is widely used in games since it uses a heuristic to make performance improvements.

In your case, the heuristic could be the Manhattan Distance metric to calculate the distance between your grid elements. This distance metric takes into consideration the total of the differences in the X and Y coordinates (which unlike euclidean distance, does not allow for diagonal traversal).

To use this algorithm however, you would need to make a graph representation of your map, something like below:

迷宫图表示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM