I have a lot of enemies on a map and I want to make them following a character on screen.
What is the most efficient method for doing this, so it will work smooth with 200+ enemies?
Thx for your help!
I have a lot of enemies on a map and I want to make them following a character on screen.
What is the most efficient method for doing this, so it will work smooth with 200+ enemies?
Thx for your help!
It depends. Do the enemies need to avoid obstacles, or just choose the shortest path towards the enemy every frame?
The easiest way is to write a code block in your enterFrame loop that does something like this:
for i = 1, #enemiesList do local distanceX = hero.x - enemiesList[i].x local distanceY = hero.y - enemiesList[i].y local angleRadians = math.atan2(distanceY, distanceX) local angleDegrees = math.deg(angleRadians) local enemySpeed = 5 local enemyMoveDistanceX = enemySpeed\*math.cos(angleDegrees) local enemyMoveDistanceY = enemySpeed\*math.sin(angleDegrees) enemy.x = enemy.x + enemyMoveDistanceX enemy.y = enemy.y + enemyMoveDistanceY end
Try this and see if this works. You might have to switch some values around or add multiples of 90 to some parts, if your enemies would happen to move in the exact opposite direction, but generally this is the way for simple “move-towards-hero” code.
Let me know if this works, if you understand this and if it’s fast enough. Step 2 is further optimisation for speed.
Sorry for my late feedback! Thank you so much for your code sample. It really helped me a lot!
It depends. Do the enemies need to avoid obstacles, or just choose the shortest path towards the enemy every frame?
The easiest way is to write a code block in your enterFrame loop that does something like this:
for i = 1, #enemiesList do local distanceX = hero.x - enemiesList[i].x local distanceY = hero.y - enemiesList[i].y local angleRadians = math.atan2(distanceY, distanceX) local angleDegrees = math.deg(angleRadians) local enemySpeed = 5 local enemyMoveDistanceX = enemySpeed\*math.cos(angleDegrees) local enemyMoveDistanceY = enemySpeed\*math.sin(angleDegrees) enemy.x = enemy.x + enemyMoveDistanceX enemy.y = enemy.y + enemyMoveDistanceY end
Try this and see if this works. You might have to switch some values around or add multiples of 90 to some parts, if your enemies would happen to move in the exact opposite direction, but generally this is the way for simple “move-towards-hero” code.
Let me know if this works, if you understand this and if it’s fast enough. Step 2 is further optimisation for speed.
Sorry for my late feedback! Thank you so much for your code sample. It really helped me a lot!