Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:

   this->enemyVel.x = -this->enemyVel.x;

   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.

share|improve this question
up vote 3 down vote accepted

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) ...
share|improve this answer
Thank you, That does it!! – nullPointer2 Nov 18 '12 at 19:37

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.