Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Enemy movement to Player  (Read 2826 times)

0 Members and 1 Guest are viewing this topic.

JasonMcG

  • Newbie
  • *
  • Posts: 10
    • View Profile
Enemy movement to Player
« on: September 19, 2017, 09:42:07 pm »
I have a Player class that houses my player.
I have an Enemy class that houses my enemy.

I want an enemy to appear at the center of the screen and then get the position if the player and move in that direction, in a straight line.
It must not follow but rather get the position of the player at a point in time and move in a straight line to that position and off the screen.
I can get it to move to the player using vector maths, but how do I make it continue to go off the screen in that straight line?
I do I get the player's position? I get the position but it's the live position that the player is moving in which is constantly updated.
How do I store these enemies? Using a vector, but how to go about it?

AlexAUT

  • Sr. Member
  • ****
  • Posts: 396
    • View Profile
Re: Enemy movement to Player
« Reply #1 on: September 19, 2017, 09:58:59 pm »
1)
Your enemy class should store the movement direction. Set it only once, when you spawn the enemy in the middle of the screen. Then use this static movement direction to move the enemy without following the player.

Hint: store the movement direction as a unit vector so you can scale the speed easily. (multiply with a scalar)

2)
Yes, a vector is a good choice, simply push them when spawning, and remove them when you want to destroy them. This is the simplest approach and will get you far (> 1000 enemies shouldn't be a problem).

(The next part is only important if you need a lot enemies and spawn/despawn them rapidly, 99% this is not important for smaller games)
If you need more and run into performance troubles, you could add a "isAlive" flag, and reuse dead enemies when spawning new ones. This will save you realloc(s) and copying data inside the vector (erase) when your enemy count wont increase anymore.
When your enemies die in the same order as they spawn and you have a maximum enemy count, a ring buffer is also an option.

AlexAUT
« Last Edit: September 19, 2017, 10:06:07 pm by AlexAUT »