Here's a really awesome technique I'm working with. For your enemy, calculate all the directions to move, figure out the priority of moving in that direction, and add them all together. Use the result to calculate your direction.
To begin with, we create two variables:
- Code: Select all
double aimXV;
double aimYV;
Now we add the direction towards the player, using our exceptionally useful
xdist and ydist functions:
- Code: Select all
double ang = direction(x, y, player.x, player.y); // calculate the direction towards the player
aimXV += xdist(ang, 5);
aimYV += ydist(ang, 5);
In this case we used 5 as our distance. This will act as the 'priority' of the movement. A bigger number means we're more likely to move in that direction. If you had more than one player to chase, you'd have to do this in a loop, and calculate the priority based on how close the player is, and maybe other factors such as the player's health.
Now, for avoiding stuff. Let's make a sensor actor which covers the area we want to check. Then we'll use getAllActorsInCollision to check what actors are touching the sensor, loop through them and check their stats, and decide whether we want to move towards them or away from them, and how important it is. Then use xdist and ydist to increase aimXV and aimYV by the appropriate amount - an asteroid that's further away is not so important to move away from as one that is close. Also a larger or faster moving asteroid may be more important to run from.
Once we've added in all our factors, we check the size of our variables:
- Code: Select all
if (distance(0, 0, aimXV, aimYV) > 1)
You can compare it with a larger or smaller value depending on how precise you want to be. If true, then we need to move. So we calculate the direction to move in:
- Code: Select all
double aimAng = direction(0, 0, aimXV, aimYV);
That's the direction we need to move in. So we use whatever system we want to adjust our velocity to that direction, and there we are! You could also store the distance we checked, and use it again to adjust our velocity, if you wanted to have different speeds.
Then add an else, so in the event we don't have to move, we can either slow to a stop, or just move randomly, or whatever.