Cool Way To Stop Motion Without Conditional

Lots of students working on CSD Unit 3 Lesson 14 (Animated Scene) ask how to stop a sprite’s movement at a certain place. Clearly, this is something to do with a conditional (e.g. IF) statement, but those are introduced in lesson 15.

Here is some code that does it using only random numbers.. When I saw it, my student had only 1 level of randomness. His code was:

blueAlien.x = randomNumber(blueAlien.x, 330);

This makes it so the x value never gets higher than 330. Of course, it could get to 330 the first time the draw() function runs. And in theory, it might never get there.

I thought about this a little and realized we can slow the movement down by adding more random numbers like this:

blueAlien.x = randomNumber(blueAlien.x, randomNumber(blueAlien.x, 330));

The more levels you add, the longer it will take for the sprite to get to 330. But all of them will stop @ 330.

Pretty cool discovery!