Moving Things Around

Now that you've learned how to draw things, it's time to make them move. To make something move, you simply have to change the x and y position on the canvas, each time the script goes around the draw loop. This is why you hd to learn how to draw things using variables - so the x and y position could VARY and all the parts of the drawing would move together. However, there are a few extra tricks you need to learn:

  1. You should control how much time it takes to go around the draw loop. This is the frameRate of your animation. You can set the frameRate in the setup function by coding:
                frameRate(30); //30 frames per second
            
  2. In the draw function, you should clear the background at the start of every loop. If you don't do this, moving objects will leave a trail of previous drawings behind them.
  3. It's a good idea to create variables to hold both the position and the speed of your moving object. The speed is how much you change the position each time around the draw loop.

Click here to see a simple example of a moving object.


Now let's add some code to stop the object from leaving the canvas. We need to use "if" statements to detect whether the object's position has moved off the canvas. If it has, then we could reverse the direction of movement by making the speed the negative of what it was. If the speed was already negative, the negative of a negative is positive. (See, all that Math stuff is useful!) Click here for the example.

Now YOU try it. You may start by copying code from this example, but then change it to make it more interesting:

Show off your work by making a new web page linked from your portfolio.