Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I get the difference between two numbers without subtraction?

Asked by
Mystdar 352 Moderation Voter
8 years ago

I am making a game where you have units on a grid and can move them around. Presuming a unit is at green and they want to move to pink, how can I see that pink is only 4 tiles away? As a point of reference, 0,0 is black, and 4,4 is white. Red is the path, how can I tell they have only crossed 4 tiles? Green is 0,2 and Pink is 2,0 if you add the difference of those numbers you get 4 however, in programming if you do something like:

green - pink

you're getting

 0, 2 - 2, 0

which is

-2 + 2

so 0 and this makes it seem they haven't moved, so my question is how can I get the difference between two numbers without subtraction, because this won't work here.

0
shouldnt it be 3 values? 0,2,0???? AND it should be Y-Y Z-Z X-X i think ConnorXV 5 — 8y
0
Yeah, of course, i'm just doing it on a 2d perspectie at the moment, still an input on answering the question? Thanks! Mystdar 352 — 8y
0
Since all you want is distance, and distance is a series of positive values (regardless of position like displacement), you can just math.abs() every single value and add them. This wouldn't be the distance formula, which would give you the length of a diagonal between the two points referenced. Legojoker 345 — 8y
1
If you subtract oldX by newX and oldZ by newZ, you'll get -2 and 2, if we add the absolute values of both of the result, then add them together, you'll get 4, which is the distance. LegitimatlyMe 519 — 8y
View all comments (3 more)
1
EXAMPLE: oldX: 10 oldY:0 newX:5 newY: 10 10 - 5 = 5, 0 - 10 = -10 abs(5)+abs(10)=15 LegitimatlyMe 519 — 8y
0
magnitude YellowoTide 1992 — 8y
0
Thank, you LegitmatlyMe i'll test that tomorrow, LegoJoker, as you can see, I am measuring the grid not studs Mystdar 352 — 8y

1 answer

Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

If you want the absolute difference, use math.abs(a-b) to get a positive number. The non-diagonal distance between two points on a grid is abs(x1-x2)+abs(y1-y2).

0
You can't subtract two numbers without subtraction, by the way. 1waffle1 2908 — 8y
Ad

Answer this question