Lesson 2 of 5

🏃 Variables & Animation

Learn how to make things move using variables

🎬 Making Things Move

So far, our drawings have been static (they don't move). But here's a secret: the draw() function runs over and over, about 60 times per second!

If we change something each time draw() runs, it creates animation. To do this, we need variables.

📦 What are Variables?

A variable is like a labeled box that stores a value. You can put something in it, look at what's inside, or change what's in it.

🔑 Creating Variables

let x = 100;        // Create a variable named 'x' with value 100
let speed = 2;      // Create a variable named 'speed' with value 2
let color = 255;    // Create a variable named 'color' with value 255

🎉 It moves! But wait... it disappears off the edge. We'll fix that in Lesson 3!

⚡ Controlling Speed

The number you add to the position each frame is the speed. Bigger numbers = faster movement!

🧭 Moving in Any Direction

You can move things in any direction by changing both x AND y:

Direction

  • → Right: x = x + speed
  • ← Left: x = x - speed
  • ↓ Down: y = y + speed
  • ↑ Up: y = y - speed

Diagonal

Change both x and y at the same time to move diagonally!

🏆 Challenge: Growing Circle

Variables aren't just for position! You can animate ANYTHING. Make a circle that starts small and grows bigger over time.

🌈 Animating Colors

You can animate colors too! Remember, colors go from 0 to 255.

💡 The if statement resets the color when it goes above 255. We'll learn more about this in Lesson 3!

🎨 Final Project: Animated Scene

Create a scene with at least one moving element! Ideas:

  • • ☀️ A sun that moves across the sky
  • • 🚗 A car driving across the screen
  • • 🎈 A balloon floating upward
  • • 🐟 A fish swimming
  • • ⭐ A star that twinkles (size changes)

📝 What You Learned

Concepts

  • ✅ Variables store values
  • ✅ draw() runs 60 times per second
  • ✅ Changing variables creates animation
  • ✅ Speed = how much you change per frame

Syntax

  • let name = value;
  • x = x + 1;
  • ✅ Direction: +/- for different ways