Moving with Arrow Keys
How can I make a player move around the screen using the arrow keys?
The beginning of every game is normally having a character that the player can control.
Step 1: Spawn a Hero for each player
First, spawn a Hero unit for each player in the game that the player can control.
We will define what a Hero is in the next step.
pub game fn World.Main() {
SpawnEachPlayer owner {
Subspawn unit {
Hero
}
}
}
- We use Subspawn to spawn the
Herounit for each player so that if the player leaves the game, theirHerowill be automatically removed from the game as well.
Step 2: Make the Hero move
Use the IsButtonDown function to check if a specific key is pressed. You can check the state of the arrow keys individually every tick and apply movement to the player's position accordingly:
pub fn unit.Hero([owner]) {
use body=this, radius=1, shape=Circle
Body(pos=@(0, 0))
PolygonSprite(color=#0f0)
PolygonCollider(category=Category:Default)
on BeforePhysics {
let direction = @(0, 0)
if IsButtonDown(ArrowLeft) { direction += @(-1, 0) }
if IsButtonDown(ArrowRight) { direction += @(1, 0) }
if IsButtonDown(ArrowUp) { direction += @(0, -1) }
if IsButtonDown(ArrowDown) { direction += @(0, 1) }
if direction == @(0, 0) { continue }
Move(0.5 * direction)
}
}
In this example, every tick we apply a small movement to the player's position based on the direction of the arrow keys. We do this before the physics simulation step of each tick so that the player's movement is taken into account when the physics simulation runs.
WASD support
The WASD keys are a common alternative to the arrow keys for movement in games, as they let players keep their right hand on the mouse while moving with their left hand.
The WASD keys are automatically mapped to the Arrow Keys, so you don't normally have to do anything special to support WASD movement.
If your game uses KeyW, KeyA, KeyS, or KeyD anywhere in your code,
it is assumed you are using them for purposes other than movement and so the automatic remapping to the arrow keys will be disabled.
See Inputs > Unification of Inputs > Automatic Unification for more details.
Full Code Listing
pub game fn World.Main() {
SpawnEachPlayer owner {
Subspawn unit {
Hero
}
}
}
pub fn unit.Hero([owner]) {
use body=this, radius=1, shape=Circle
Body(pos=@(0, 0))
PolygonSprite(color=#0f0)
PolygonCollider(category=Category:Default)
on BeforePhysics {
let direction = @(0, 0)
if IsButtonDown(ArrowLeft) { direction += @(-1, 0) }
if IsButtonDown(ArrowRight) { direction += @(1, 0) }
if IsButtonDown(ArrowUp) { direction += @(0, -1) }
if IsButtonDown(ArrowDown) { direction += @(0, 1) }
if direction == @(0, 0) { continue }
Move(0.5 * direction)
}
}