2026年1月25日日曜日

how to add and use the Keyboard Controls 

 📋

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 PressedAction (The Block)Direction
Up Arrowchange y by (10)Moves Up
Down Arrowchange y by (-10)Moves Down
Right Arrowchange x by (10)Moves Right
Left Arrowchange x by (-10)Moves Left

How to build the script:

  1. Grab a When 🚩 clicked block.

  2. Snap a forever loop underneath it.

  3. Inside the loop, put an if < > then block.

  4. Inside the "diamond" shape of the if block, drop a key [up arrow] pressed? (from the Sensing category).

  5. Inside that, put change y by (10).

  6. Repeat this for the other three directions!

Why do it this way? If you use the "Easy Way" (When [key] pressed blocks), there is a tiny delay when you hold the key down (like when you're typing and wait for a letter to repeat). The forever loop 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 件のコメント:

コメントを投稿