Here is the newest problem I am running into. I have a class called Projectiles which holds the basic makeup of a projectile. It’s coordinates, and the image which it uses. Here is the basic structure:
class Projectile
{
private:
void load();
public:
SDL_Surface *surface;
SDL_Surface* returnSurface()
{
return surface;
}
Projectile( int );
void coordinates( int, int );
int type;
int width, height;
int positionX, positionY;
bool alive;
};
Projectile::Projectile( int type )
{
type = 1;
alive = true;
width = 83;
height = 46;
}
void Projectile::load()
{
SDL_Surface* loadedImage = NULL;
loadedImage = IMG_Load( "hero.png" );
surface = SDL_DisplayFormat( loadedImage );
SDL_FreeSurface( loadedImage );
}
void Projectile::coordinates( int x, int y )
{
positionX = x;
positionY = y;
}
Now, I also have my hero class which holds the projectile objects in a vector like such:
vector< Projectile > projectiles;
I have a method in the hero class which makes a new projectile and pushes it into this vector like so:
void Hero::newProjectile( int type )
{
projectiles.push_back( Projectile( type ) );
projectileCount++;
}
and then a draw method which is called at the very end of my main loop which does the following:
void Hero::drawProjectileState( SDL_Surface* destination )
{
for( int i = 0; i < projectileCount; i++ )
{
SDL_Rect offset;
offset.x = positionX;
offset.y = positionY;
SDL_BlitSurface( projectiles[i].returnSurface(), NULL, destination, &offset );
}
}
conceptually, I thought this would work just fine. Originally my projectile class held ALL of the projectiles coordinates in its own vector, but I came across a problem when I wanted to delete them. Since they all used the same surface resource, deleting one while another was on the screen would cause the game to crash. I thought this would solve the problem ( each having their own surface resource ), but I am getting
Access violation reading location 0xccccccf8.
when it attempts to draw the projectile at :
SDL_BlitSurface( projectiles[i].returnSurface(), NULL, destination, &offset );
I have a feeling i am misunderstanding the way the surface referencing works. What would be the best way to give each projectile its own surface, so that I can delete them independently?
edit: just to clear up possible confusion, I want to be able to FREE the surfaces independently. Freeing a surface once one projectile dies, but another was still on the screen is what was causing the crashes initially.
In the code above, you never loaded a surface. You never even initialized
surface, so it’s pointing off in space, hence the access violation indrawProjectileStatewhen you do this: