Animation and variables — moving an object
the examples in this lesson are written for Processing Python Mode. If you work in the recommended environment Thonny + py5, most of the code stays the same, and names with a capital letter in the middle are written in lower case with an underscore:
mouseX → mouse_x, noStroke() → no_stroke(). See the table of differences.What actually is animation?
Animation in Processing is changing the picture quickly, many times a second.
The function draw() repeats all the time and draws a new picture every time.
If we change the position of an object a little in every repetition — we get movement.
Animation = draw → move → draw → move → (many times a second)
Why are variables important?
Variables keep the state of an object — where the object is at every moment.
- x — the horizontal position
- y — the vertical position
- dx — the speed along the x axis
- dy — the speed along the y axis
A simple ball animation
x = 50
y = 200
dx = 3
def setup():
size(600, 400)
frameRate(60)
def draw():
global x, dx
background(220)
fill(255, 0, 0)
ellipse(x, y, 50, 50)
x += dx
if x > width - 25 or x < 25:
dx = -dx
How does this work?
- the screen is cleared (
background()) - the object is drawn
- the position changes
Animating a picture (sprite)
Now we use a picture instead of a shape.
img = None
x = 0
y = 150
dx = 3
def setup():
global img
size(600, 400)
img = loadImage("character.png")
def draw():
global x, dx
background(220)
image(img, x, y)
x += dx
if x > width - img.width or x < 0:
dx = -dx
img must be available in the draw() function.
If you define it only in setup(), it will not work.
This does NOT work:
def setup():
img = loadImage("character.png")
Because img is not a global variable.
Use
img.width
img.height
to get the exact dimensions.
- Change the speed (
dx) - Change the starting position
- Use your own picture
Why do we use global?
Variables defined outside a function must be marked as global to be changed in draw().
global x, dx
global, changing the value will not work as you expect.
The speed of animation — frameRate()
frameRate(60) means 60 frames per second.
frameRate(10)— slowframeRate(120)— fast
Mini project: an animated scene
- a picture of a character
- a background
- additional objects
Next lesson
Interaction with the mouse → (SR)
Related topics
Check your knowledge
Open the quiz
Mini quiz: animation
1. Why do we write global x in draw()?
2. What happens if you leave out background() in draw()?
