Russell Gordon

# Defining an Animation

## 12 October, 2020

Before following this tutorial, be sure you've created a new animation file to work within.

## Drawing on the Canvas

Say that we want a square to appear on the canvas of this animation.

Anything we want to be animated must be specified in the `draw` function.

Add this code at line 30:

``````// Draw a square in the middle of the canvas
canvas.drawRectangle(at: Point(x: 250, y: 250), width: 50, height: 50, anchoredBy: .centre)
``````

Run the animation. It appears to be static – the square does not move.

Remember, though – what's actually happening is that a new square is being drawn about sixty times per second over the prior square.

It's just that right now, the square is always drawn in the same position.

## Defining a Property

Let's add a property. After line 17, add this property:

``````// Vertical position
var y = 250
``````

The scope of this property is the entire `MovingSquare` class – we can change it's value anywhere inside the class.

Adjust the line of code that draws the rectangle, so that the point the square is drawn at is no longer:

``````Point(x: 250, y: 250)
``````

... but is instead:

``````Point(x: 250, y: y)
``````

Now run the animation. What's changed?

Nothing – the `y` property is initialized at 250, and never changes.

## Changing a Property to Drive the Animation

Add the following line of code above the line where the square is drawn, inside the `draw` method:

``````// Change the vertical position
y += 1
``````

Now run the animation. Why does the square move?

Remember, the `draw` function is automatically run about sixty times per second by the `Animation` project.

Since we are changing the `y` property (adding 1 to its value each time), and the square is drawn using that property, the square moves.

If you're still not quite sure what's going on, add this line of code inside the `draw` function:

``````print("The y position is: \(y)")
``````