A problem today unfortunately [sad]. I have started with adding an enemy. The Enemy has its own constructor so that any image can be loaded. I also have two states: ENTERING and STATIONARY. The idea being that the enemy starts offscreen in the ENTERING state and when it reaches its final point (m_FinalX, m_FinalY) it will stop.
To get the Enemy going in the right direction I take the differences (m_X - m_FinalX) and the same for y. This gives me a vector going from inital to final positions. But so that it doesn't jump in one step I find the unit vector in this direction by dividing through by the length of the vector. I then use the components of the unit vector as the x and y velocities of the Enemy. (All of this is done in the constructor).
However, to get the nesseccary precision I use floats for everything (otherwise m_VelX and m_VelY equal zero). But then this gives me the problem that when checking to see if the Enemy has reached its final point it is never *exactly* there. It is always out by a few decimal places and so it never goes to the STATIONARY state.
I've tried recalculating the vector in an UpdateEnemy() function but that just leads to the Enemy vibrating about the final point.
Here's the code:
Enemy::Enemy(SDL_Surface* image, float x, float y, float finalX, float finalY)
m_Image = image;
m_X = x;
m_Y = y;
m_FinalX = finalX;
m_FinalY = finalY;
m_State = ENTERING;
float delta_x = (m_FinalX - m_X);
float delta_y = (m_FinalY - m_Y);
float length = sqrt( pow(delta_x, 2) + pow(delta_y, 2) );
m_VelX = delta_x / length;
m_VelY = delta_y / length;
if ( (m_State == ENTERING) && (m_X == m_FinalX) && (m_Y == m_FinalY) )
m_State = STATIONARY;
if (m_State == STATIONARY)
m_VelX = 0;
m_VelY = 0;
I will also post this in the forums, see if I can get any help there as well.
Thanks for reading
EDIT: Now solved thanks to WanMaster. Now I just check to make sure the difference between m_X and m_FinalX is less than 0.1.