🏀 Conditionals & Bounce
Teach your code to make decisions with if statements
🤔 Making Decisions
In Lesson 2, our ball flew off the screen and never came back! We need to teach our code to make decisions: "IF the ball hits the edge, THEN do something."
This is called a conditional — code that only runs when a condition is true.
🔀 The if Statement
🔑 if Syntax
if (condition) {
// This code only runs if condition is true
}Comparisons
x > 100greater thanx < 100less thanx === 100equalsx >= 100greater or equalx <= 100less or equal
Canvas Size
p5.js gives you special variables:
width= canvas widthheight= canvas height
Edges
- Left edge:
x < 0 - Right edge:
x > width - Top edge:
y < 0 - Bottom edge:
y > height
🎉 Now it wraps around! But what if we want it to bounce instead?
🔄 Making it Bounce
To bounce, we reverse the direction. If speed is positive (moving right), we make it negative (moving left), and vice versa.
🔑 The Bounce Trick
speed = speed * -1; // Flip the direction! // or shorter: speed = -speed;
📦 Bouncing on All Sides
For a ball that bounces all around, we need separate speed variables for x and y:
💡 The || means "OR" — the code runs if EITHER condition is true.
↔️ if...else
Sometimes you want to do one thing if a condition is true, and something ELSE if it's false:
🏆 Challenge: DVD Screensaver
Remember the old DVD logo that bounced around the screen? Make a rectangle that bounces off all the walls!
🎨 Final Project: Bouncing Ball with Trail
Create a ball that bounces around and leaves a fading trail behind it! Hint: Use a semi-transparent background instead of a solid one.
📝 What You Learned
Concepts
- ✅ Conditionals check if something is true
- ✅ Comparisons: >, <, ===, >=, <=
- ✅ Bouncing = reversing speed
- ✅ || means OR
Syntax
- ✅
if (condition) { } - ✅
if...else - ✅
speed = -speed