Reputation: 1335
I am creating a game in Java and have a grid of squares that make up the playable area. The player has certain targets and I need to work out how far away the player is from those targets using the x an y coordinate values of the squares. So if the player was on cell 1,1 I would need to know that it was 2 squares away (2 movement inputs) from cell 2,2 - you cannot move diagonally.
I found Euclidean distance formula but I'm unsure about how to convert this to Java and it doesn't take into account that I can't move diagonally so I'm not sure if this is even applicable.
Is there some simple formula that I am missing? I couldn't seem to find one. Thanks.
Upvotes: 0
Views: 2628
Reputation: 58858
Yes, there is a simple formula: Math.abs(x1 - x2) + Math.abs(y1 - y2)
Math.abs
is the absolute value function - if the argument is a positive number then it returns that; otherwise it returns the corresponding positive number (so Math.abs(-5)
returns 5)
Upvotes: 7