[英]Calculating the distance between two squares on a grid - Java
I am creating a game in Java and have a grid of squares that make up the playable area. 我正在用Java创建游戏,并且具有构成可玩区域的正方形网格。 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.
玩家具有某些目标,我需要使用正方形的x和y坐标值来计算玩家与这些目标的距离。 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.
因此,如果玩家在单元格1,1上,我需要知道它与单元格2,2相距2格(2个运动输入)-您不能对角移动。
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. 我找到了欧几里得距离公式,但不确定如何将其转换为Java,也没有考虑到我不能对角移动,因此我不确定这是否适用。
Is there some simple formula that I am missing? 我缺少一些简单的公式吗? I couldn't seem to find one.
我似乎找不到一个。 Thanks.
谢谢。
Yes, there is a simple formula: Math.abs(x1 - x2) + Math.abs(y1 - y2)
是的,有一个简单的公式:
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; Math.abs
是绝对值函数-如果参数为正数,则返回该值; otherwise it returns the corresponding positive number (so Math.abs(-5)
returns 5) 否则,它将返回相应的正数(因此
Math.abs(-5)
返回5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.