Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

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!! –  BadSniper Nov 18 '12 at 19:37
add comment

Your Answer

 
discard

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.