• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Move unit X distance towards unit2

Level 20
Joined
Feb 27, 2019
Messages
593
set x1 = GetUnitX(u1)
set y1 = GetUnitY(u1)
set x2 = GetUnitX(u2)
set y2 = GetUnitY(u2)
set angle = Atan2(y2 - y1, x2 - x1)
set x1 = x1 + distance * Cos(angle)
set y1 = y1 + distance * Sin(angle)
SetUnitX(u1, x1)
SetUnitY(u1, y1)
 

Dr Super Good

Spell Reviewer
Level 64
Joined
Jan 18, 2005
Messages
27,202
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.
 
Top