OK, here's the problem. I have a grid of 18x18 squares of equal size. I am trying to write a function that takes the coordinates of the current square (xCurrent, yCurrent) and the coordinates of the target square (xTarget, yTarget) and calculates the distance (in squares) between these two points.
Why am I doing this? It's in order to calculate if the distance exceeds the playes allowed maximum movement. The player can move in any of eight directions (up, down, left, right and the four diagonals).
So far, I am able to calculate the distance between the two points if they are on the same horizontal or vertical plane (as the distance will either be xTarget-xCurrent or yTarget-yCurrent respectively). I have written code that calculates the distance between any two points but the problem is that it assumes the player is moving in an 'L-shape' to the target square (therefore the distance would be the sum of the difference between xTarget and xCurrent and yTarget and yCurrent). This is all well and good but it has severe faults as it always calculates the distance as greater than is possible if one were to use a combination of diagonal, horizontal and vertical lines.
Here is the function as it stands now:
FUNCTION CalculateDistance(xCurrent AS INTEGER, yCurrent AS INTEGER, xTarget AS INTEGER, yTarget AS INTEGER)
Distance = -1
IF xTarget = xCurrent
`The two points are on a horizontal plane from each other
Distance = yTarget-yCurrent
IF Distance <0 THEN Distance = Distance*-1
GOTO EndOfCalculateDistance
ENDIF
IF yTarget = yCurrent
`The two points are on a vertical plane from each other
Distance = xTarget-xCurrent
IF Distance <0 THEN Distance = Distance*-1
GOTO EndOfCalculateDistance
ENDIF
IF xCurrent = yCurrent AND xTarget = yTarget
`The shortest distance between these points is definitely a diagonal line
Distance = xTarget-xCurrent
IF Distance <0 THEN Distance = Distance*-1
GOTO EndOfCalculateDistance
ENDIF
`This needs to be sorted as it calculates an 'L' shape to the target
D1 = yTarget-yCurrent
IF D1 <0 THEN D1 = D1*-1
D2 =xTarget-xCurrent
IF D2 <0 THEN D2 = D2*-1
Distance = D1+D2
EndOfCalculateDistance:
ENDFUNCTION Distance
If anyone could help me out I would be very grateful,
Thanks,