Its only appearing for a split second because the collision returns back to false after you have a collision.
if( ( box.x < 0 ) || ( box.x + MOVER_WIDTH > SCREEN_WIDTH ) || ( check_collision( box, wall ) ) )
{
//Move back
box.x -= xVel;
}
//If the Mover went too far up or down or has collided with the wall
if( ( box.y < 0 ) || ( box.y + MOVER_HEIGHT > SCREEN_HEIGHT ) || ( check_collision( box, wall ) ) )
{
//Move back
box.y -= yVel;
}
}
The two bold underlined lines are always going to make your box "bounce" off whatever it is colliding with, making the collision become false again. Which is why you are only seeing the image for a split second and then it disappears. You are going about it the right way, but because you are checking for a collision each time you move the statement is no longer true once you do have a collision because the box "bounces" off the wall. Honestly, that collision code isn't that optimal for returning whether or not a collision is happening because it causes that "bounce" effect.
Doing it this way will draw your image as long as you are having a "collision". i.e you need to be moving the box into the wall.
Code: Select all
void Mover::move()
{
//Move the Mover left or right
box.x += xVel;
//If the Mover went too far to the left or right or has collided with the wall
if( ( box.x < 0 ) || ( box.x + MOVER_WIDTH > SCREEN_WIDTH ) || ( check_collision( box, wall ) ) )
{
//Move back
box.x -= xVel;
apply_surface( 200, 300, dot, screen );
}
//Move the Mover up or down
box.y += yVel;
//If the Mover went too far up or down or has collided with the wall
if( ( box.y < 0 ) || ( box.y + MOVER_HEIGHT > SCREEN_HEIGHT ) || ( check_collision( box, wall ) ) )
{
//Move back
box.y -= yVel;
apply_surface( 200, 300, dot, screen );
}
}
Alternatively you could store the collision in a bool flag
Code: Select all
//somewhere in your main.cpp
bool collision = false;
Code: Select all
void Mover::move()
{
//Move the Mover left or right
box.x += xVel;
//If the Mover went too far to the left or right or has collided with the wall
if( ( box.x < 0 ) || ( box.x + MOVER_WIDTH > SCREEN_WIDTH ) || ( check_collision( box, wall ) ) )
{
//Move back
box.x -= xVel;
collision = true;
}
//Move the Mover up or down
box.y += yVel;
//If the Mover went too far up or down or has collided with the wall
if( ( box.y < 0 ) || ( box.y + MOVER_HEIGHT > SCREEN_HEIGHT ) || ( check_collision( box, wall ) ) )
{
//Move back
box.y -= yVel;
collision = true;
}
}
Code: Select all
//somewhere in your main loop
if (collision)
{
apply_surface( 200, 300, dot, screen );
}