• 🏆 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!
  • 🏆 Hive's 6th HD Modeling Contest: Mechanical is now open! Design and model a mechanical creature, mechanized animal, a futuristic robotic being, or anything else your imagination can tinker with! 📅 Submissions close on June 30, 2024. Don't miss this opportunity to let your creativity shine! Enter now and show us your mechanical masterpiece! 🔗 Click here to enter!

Move unit X distance towards unit2

Dr Super Good

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