# enemy behavior with boundary to change direction

I'm doing space shooter kind of game, the logic is to reflect the enemy if it hits the boundary. With my logic, sometimes enemy behaves like flickering instead of changing the velocity. It's like trapped in the boundary and checking for if loops. This is my code for velocity changing:

if(this->enemyPos.x>14)
{
this->enemyVel.x = -this->enemyVel.x;
}

if(this->enemyPos.x<-14)
{
this->enemyVel.x = -this->enemyVel.x;
}

How can I get around this? Its going out of boundary and don't know where to go and after sometimes its coming into field. I know whats the problem is, I dont know how to get around this problem.

-

Your problem is that you are always toggling the enemy's velocity, even if it's already moving in the direction you want.

Say that in frame 1 the enemy is moving left and is at position -15. Your check now makes it moving right. At frame 2, it's moving right and at position -14.001, due to rounding errors, frame time differences, etc. Your check now makes it going left again.

Either set your velocity to the value you want explicitly, e.g.

velocity.x = abs(velocity.x); // go right
velocity.x = -abs(velocity.x); // go left

Or change your checks to include both position and direction of movement, e.g.

if (position.x < -14 && velocity.x < 0) ...
-
Thank you, That does it!! – nullPointer2 Nov 18 '12 at 19:37