 • entries
55
55
• views
25081

# Our Velocity II

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, int x, int y)// -- Enemy constructor so that any image can be loadedEnemy::Enemy(SDL_Surface* image, float x, float y, float finalX, float finalY){	// Assign all the arguments given	m_Image = image;	m_X = x;	m_Y = y;	m_FinalX = finalX;	m_FinalY = finalY;	// Start with entering	m_State = ENTERING;	// Start the Enemy going in the right direction	// Find the components of the vector to the final point	float delta_x = (m_FinalX - m_X);	float delta_y = (m_FinalY - m_Y);	// Find the length of this vector	float length = sqrt( pow(delta_x, 2) + pow(delta_y, 2) );	// Get the components of the unit vector in this direction	// These are the velocities to use	m_VelX = delta_x / length;	m_VelY = delta_y / length;}// void Enemy::UpdateEnemy()// -- Updates the enemy's state (inc. velocity etc)void Enemy::UpdateEnemy(){	// Change the state if nesseccary	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.

-AEdmonds

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.

There are no comments to display.

## Create an account

Register a new account