📋
The "Move and Bounce" script is often considered the "Hello World" of Scratch. It is the simplest way to make a Sprite (your character) move around the screen autonomously without it flying off into the void.
Instead of your character walking off-screen and disappearing forever, this script tells it: "Keep moving, and if you hit a wall, turn around."
The Recipe: How to Build It
To create this, you snap together four specific blocks in the Scripts Area:
| Block Type | The Specific Block | What it Does |
| Events | When green flag clicked | Starts the program. |
| Control | forever | A loop that keeps the code running non-stop. |
| Motion | move (10) steps | Pushes the sprite forward. |
| Motion | if on edge, bounce | Detects the edge of the stage and flips the direction. |
What the code looks like:
When 🚩 clickedforevermove (10) stepsif on edge, bounce
The "Upside-Down" Problem (And the Fix)
By default, Scratch sprites rotate $360^\circ$. This means when your character hits the right wall and "bounces" back to the left, it will often flip upside down.
To fix this and keep your character walking upright, you need one extra block:
set rotation style [left-right]
Place this block at the very top (just under the Green Flag), and your sprite will flip horizontally like a 2D platformer character rather than doing a headstand.
Why this script matters
This script teaches you the two most important concepts in programming:
Loops (
forever): Computers are great at doing the same thing over and over without getting bored.Conditionals (
if on edge): This is basic logic. The computer is constantly checking a "condition" (Am I touching the edge?) and performing an "action" (Bounce!) only when that condition is true.
Pro-Tip: Try changing the number in the
move (10) stepsblock. Change it to 2 for a slow crawl, or 50 if you want to see your sprite have a caffeinated breakdown.
Would you like to know how to add Keyboard Controls so you can move the sprite yourself using the arrow keys?
📋
0 件のコメント:
コメントを投稿