I'm a bit stuck with this one, I'm trying to make a sprite move back and forth forever, while the game loop is running. At first I tried to use a timer/clock function, but I couldn't get a library/function that I could use. What I have tried now though is having 2 invisible rects, one at each end of the sprite's path. So when the sprite intersects one, it's direction is reversed and so on. However in my code I can't figure out where I've gone wrong. Any thoughts? Sorry if it is a bit hard to understand in the code.
bool targmright = false; // bool for moving the sprite right
bool targmleft = true; // bool for moving the sprite left
if (targmleft == true) // "targ" is the sprite I mention
{
targ.move(-1, 0);
if (targb.intersects(targlb)) // if the sprite's bounding box intersects the left bounding box
{
targmright = true;
targmleft = false;
}
}
if (targmright == true)
{
targ.move(1, 0);
if (targb.intersects(targrb))
{
targmright = true;
targmleft = false;
}
}
You can use for better coordinates :
Ex:
// outside the game loop :
int max_left = 0
int max_right = 600 /* (supposing that youw window have 600 width ... you can change the size in the
resize // event */
float move = 1 ;
// inside the game loop :
floatRect spr_pos = targ.getPosition()
if ( spr_pos.x >= max_right )
{
move = -1
}
else if ( spr_pos.x <= max_left )
{
move = 1
}
targ.move( move , 0 )