📋
Adding keyboard controls is the first step toward making a real game! There are two ways to do this in Scratch: the "Easy Way" (using Event blocks) and the "Pro Way" (using Sensing blocks).
The "Pro Way" is much better for games because it makes the movement smooth instead of jerky.
The "Pro Way" (Smooth Movement)
In this method, we tell Scratch to constantly "listen" for a key press inside a loop.
The Logic Table
To move a sprite, you change its position on a grid. Think of the stage as a map:
X = Left and Right
Y = Up and Down
| Key Pressed | Action (The Block) | Direction |
| Up Arrow | change y by (10) | Moves Up |
| Down Arrow | change y by (-10) | Moves Down |
| Right Arrow | change x by (10) | Moves Right |
| Left Arrow | change x by (-10) | Moves Left |
How to build the script:
Grab a
When 🚩 clickedblock.Snap a
foreverloop underneath it.Inside the loop, put an
if < > thenblock.Inside the "diamond" shape of the
ifblock, drop akey [up arrow] pressed?(from the Sensing category).Inside that, put
change y by (10).Repeat this for the other three directions!
Why do it this way? If you use the "Easy Way" (
When [key] pressedblocks), there is a tiny delay when you hold the key down (like when you're typing and wait for a letter to repeat). Theforeverloop method removes that lag completely!
Combining it with "Rotation Style"
If you want your sprite to face the direction it's moving, you can add a point in direction block to each "if" statement:
Up:
point in direction (0)Down:
point in direction (180)Right:
point in direction (90)Left:
point in direction (-90)
Don't forget to set your rotation style to left-right so your sprite doesn't flip upside down when moving left!
Summary of the Coordinates
If you're feeling fancy, remember that the center of the stage is $(0, 0)$.
Maximum X is $240$ (far right).
Maximum Y is $180$ (top).
Would you like to know how to add Gravity so your character can jump and fall back down like in Mario?
📋
0 件のコメント:
コメントを投稿