I'm trying to build a projectile in SDL. I have it so that every frame I decrement a timeOfLife varriable by timeDelta and when it hits 0 the projectile is destroyed. The problem is that the statement controlling this is running the second the program starts even though the logical statement that should have to evaluate to true is actually false. Printing out the state of each variable, the program starts with isDead = true, and the if statement should only run if !isDead (!false), but it still runs right away. Why?
Projectile::Projectile() {
std::cout << "Projectile created\n";
this->direction = 0;
timeOfLife = 1000;
bool isDead = true;
projTexture.loadFromFile( "bullet.png" );
projVel = 1; // twice ship velocity
projDir = 0;
projPosX = 0;
projPosY = 0;
projCollBox = { 0, 0, 5, 5 };
timeDelta = 10;
}
void Projectile::handleEvent( SDL_Event e, int shipDirection, int shipPosX, int shipPosY ) {
if (e.key.keysym.sym == SDLK_SPACE ) {
isDead = false;
// std::cout << "just made the switch";
direction = shipDirection;
projPosX = shipPosX;
projPosY = shipPosY;
}
// std::cout << "projPosX: " << projPosX << "\n" << "projPosY: " << projPosY << "\n" << "direction: " << direction << "\n";
}
void Projectile::update() {
// isDead is true going into this function, so why does the switch statement run?
if ( timeOfLife <= 0 ) {
isDead = true;
}
if (!isDead) {
switch (direction) {
case UP: projPosY -= projVel; timeOfLife -= timeDelta; break;
case DOWN: projPosY += projVel; timeOfLife -= timeDelta; break;
case RIGHT: projPosX += projVel; timeOfLife -= timeDelta; break;
case LEFT: projPosX -= projVel; timeOfLife -= timeDelta; break;
}
}
std::cout << std::boolalpha << "isDead: " << isDead << "\n" << "timeOfLife: " << timeOfLife << "\n";
}
void Projectile::render() {
if (!isDead)
projTexture.render( projPosX, projPosY );
// std::cout << "texture rendered";
}