• Listen to a special audio message from Bill Roper to the Hive Workshop community (Bill is a former Vice President of Blizzard Entertainment, Producer, Designer, Musician, Voice Actor) 🔗Click here to hear his message!
  • Read Evilhog's interview with Gregory Alper, the original composer of the music for WarCraft: Orcs & Humans 🔗Click here to read the full interview.

Move unit X distance towards unit2

Status
Not open for further replies.

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,285
If you know the distance between the units, you can then scale the difference in their X and Y to get the desired distance. This avoids using trigonometry and only relies on Pythagoras's theorem. Below is example pesudo code.

Code:
// move u1 100 units towards u2
move = 100
x1 = GetUnitX(u1)
y1 = GetUnitY(u1)
x2 = GetUnitX(u2)
y2 = GetUnitY(u2)
dx = x2 - x1
dy = y2 - y1
distance = sqrt(dx * dx + dy * dy)
scale = move / distance
SetUnitX(u1, x1 + scale * dx)
SetUnitY(u1, y1 + scale * dy)

The distance between the two points must be larger than 0, otherwise a division by 0 error/thread crash will occur. In the above example this means that u1 and u2 must be different units that must also be at different points on the map. Since this constraint can be difficult to assure naturally, it might be good to check if the calculated distance is 0 and if so then perform some sort of fall-back logic such as moving in an arbitrary direction to avoid the division by 0.
 
Status
Not open for further replies.
Top