The way to make a player entity is straight forward, declare it in the source file , load its assets when entering the in game state and clear the assets when exiting ... no problem.
The bullets however pose a number of issues, I cant declare each bullet beforehand.... they need to be created dynamically so I create one each time the player fires, and store it in the entity vector like the player... and when the bullet collides with a wall it dies, so I delete it and erase the element in the vector it was stored in.
Code to create a bullet :
Entity_Bullet* pBullet = new Entity_Bullet;
pBullet->OnLoad(16,16,1,ENTITY_TYPE_BULLET_PLAYER);
if(Facing == ENT_DIR_RIGHT)
{
pBullet->MoveRight = true;
pBullet->MoveLeft = false;
pBullet->X = X + Width;
pBullet->Y = Y + (Height/2);
}
if(Facing == ENT_DIR_LEFT)
{
pBullet->MoveLeft = true;
pBullet->MoveRight = false;
pBullet->X = X - 20;
pBullet->Y = Y + (Height/2);
}
Entity::EntityList.push_back(pBullet);
The entity list is declared like this : std::vector<Entity*> Entity::EntityList;
The code to remove the bullet is in the ingame state loop, where it goes through the entity vector and calls up each element.
// Move , Animate and calculate actions for ALL entities
for(unsigned int i = 0; i < Entity::EntityList.size(); i++)
{
if(!Entity::EntityList) continue;
Entity::EntityList->OnLoop();
// If the entity is not a player
if(Entity::EntityList->Type != ENTITY_TYPE_PLAYER)
{
// If the Entity is suppose to be destroyed
if(Entity::EntityList->Dead == true)
{
Text::AddText("Dead one here", 10, 400);
Entity::EntityList->OnCleanup();
if(Entity::EntityList->Type == ENTITY_TYPE_BULLET_PLAYER)
{
delete Entity::EntityList;
}
Entity::EntityList.erase(Entity::EntityList.begin() + (i --));
}
}
}
The issue seems to be in the clearing up portion, I think there is a conflict in the vector when a few bullets are made and destroyed... I am thinking it is trying to store a bullet in a vector that was deleted but not cleared ?
If I remove the delete and erase portions of the entity loop it runs without crashing, just leaves bullets all over the place.
I would prefer the actual bullet class to delete the bullet during the OnCleanup() call, but using delete this crashes the game as soon as a bullet is fired, and I cant think of a way to identify the particular bullet beyond a this call.
Hmm, would the bullet object go out of scope if the pointer ( or rather the element the pointer was erased ? ).
Tips , ideas , advice welcome ... thanks.
FYI - I havent just copied the tutorials code , I have modified a number of things in the code except for portions where I like how it works, ie I havent just copy pasted someone elses code and want you to sort out the bugs.