The first problem is that draw()
is always setting the xspeed
of your object back to 10. It’s doing this every frame. So once your object has hit the right edge, yes, it’s speed is set to -10, but only for one frame! The speed is set to 10 again when draw() runs again, and so it hits the right edge again, loops this behavior over and over, and thus gets stuck at the edge.
The second problem is that your code’s logic is all over the place. Let’s see if we can’t break your sketch down into more manageable sections.
First, we will simplify draw()
. We will make it do four things:
- Move the object.
- Check if it hit the edge.
- If it did hit the edge, change the stored values that describe our object.
- Draw our object based on the values stored in the variables that describe it.
Thus our new draw()
function looks like this:
void draw(){
// Always start with a clean background!
background(255);
// Move the object.
object_move();
// Check if it hit an edge.
if( object_did_hit_edge() ){
// If it did, update its variables.
object_on_edge_hit();
}
// Now finally, draw the object.
object_draw();
}
Notice how that logic is crystal clear? I’m not even messing about with any variables in there! Next we need to write these functions:
void object_move(){
// Add the speed to the position.
object_x_position = object_x_position + object_speed;
}
boolean object_did_hit_edge(){
return( object_x_position > width );
}
void object_on_edge_hit(){
object_speed = -10;
object_is_ellipse = true;
}
void object_draw(){
if( object_is_ellipse ){
ellipse( object_x_position, height/2, 20, 20);
} else {
rect( object_x_position, height/2, 20, 20);
}
}
Notice how each of these functions is clear about what it does?
I glazed over the variables needed to know the object’s state:
float object_x_position = 0;
float object_speed = 10;
boolean object_is_ellipse = false;
Now try putting it all together yourself! Post the code of your new attempt at getting this to work.