Note: a more up-to-date version of this tutorial can be found here: http://gamefroot.com/knowledgebase/scripting-a-top-down-player-rpg-style/
Hey guys, here’s a quick rundown of how to make something move around with the keyboard.
Here’s a little game I’ve started building. I drew some terrain down, and then placed a snowman (on a regular layer).
I want to be able to move this snowman around by pressing the arrow keys, so I need to create a script. To do this, right-click on the game object, then select Add Script.
First I need to be able to tell when keys on the keyboard are being pressed. We can get the Event block for this under Input, Keyboard. Click on the block “When the player presses key” and drag it out into the empty workspace.
This block comes with backspace selected as the default key, but I want to use the arrow keys. To change the key, click on the arrow next to backspace and select right arrow from the drop down menu.
I want the snowman to move around, so I need to get a block specifically for movement. Blocks for movement and physics are under Game Mechanics, ArcadePhysics. Grab the “set velocity x” block and drag it into the block we placed down before. Make sure they snap together.
A velocity of 0 won’t move at all, so change the velocity x number to 200.
Then Save the script!
Hit Play (in the top-right corner) to see if your scripted snowman works.
Wheee! When you press the right arrow key, the snowman flies off to the right. Perfect. Let’s get the other arrow key working. Click Edit (in the top-right corner) to go back to edit mode.
To keep working on the script we started, right-click on the snowman and select Edit script.
I want the snowman to stop moving when I release the arrow key, so I need to duplicate these blocks. Right-click on the yellow event block, and select Duplicate.
Now we have two sets of these blocks.
Change one of the “presses” to “releases” by clicking on it to reveal the drop down menu.
When the key is released, I want the movement (velocity) to go back to being still. That means I need to set velocity to 0.
Now we can repeat this process to make the left arrow key make the snowman move left. Duplicate the existing blocks, and change right arrow to left arrow. Also make sure you set the velocity to -200 instead of 200. A negative velocity like -200 will move the snowman to the left instead of to the right.
Now save this, and Play the game. Awesome! Now your snowman can move left and right. What else would you add to this script? What other things should happen to the snowman?
If you have any cool ideas, let us know in the comments below.