Movement
changeX(4) moves a sprite at the same speed all the time. Games feel more
alive when sprites speed up, slow down, fall and bounce. The trick is always
the same: keep the speed in a field and change the position by the
speed in every frame.
Speed in a variable
The arrow keys change the ship's speed, not its position. Let go, and it slowly comes to a stop:
xSpeed * 0.95takes away a little speed in every frame, like friction.-
Operators.constrain(value, low, high)keeps a value between two limits. Here it keeps the ship on the stage.
Try it: change 0.95 to 0.99. Now the ship slides like on ice. With
0.8 it moves through mud.
Falling and jumping
Gravity is a speed downwards that grows a little in every frame. A jump sets the speed upwards once. Use the arrow keys:
In every frame:
ySpeed - 0.6pulls the alien down a bit harder. That is gravity.changeY(ySpeed)moves it.-
If it now touches the ground,
changeY(-ySpeed)takes the step back and the speed becomes0. It stands on the ground. -
Only on the ground does the up arrow set
ySpeed = 12. So it cannot jump in the air.
Walk off the edge, and it falls off the stage and starts again at the top.
Try it: change 0.6 and 12. What feels like the moon?
Bouncing
A speed for x and one for y let a sprite fly in any direction. To bounce, turn a
speed around: ySpeed = -ySpeed.
* 0.8 makes each bounce lower, because the bubble loses some speed on the
floor.
For a sprite that moves with move() in its direction, ifOnEdgeBounce() does
the bouncing for you, as in Scratch.
Following smoothly
Operators.lerp(from, to, 0.05) gives a value 5 % of the way from one number
to another. Do this in every frame, and a sprite glides to its target: fast when
it is far away, slow when it is close. Move the mouse over the stage:
- The green fish uses
lerp. It slows down when it comes close. -
The pink fish turns towards the mouse and moves with a steady speed.
Without the
distanceToMousePointer() > 5, it would wiggle on the spot when it reaches the mouse.
The same lerp makes a camera follow the player
smoothly:
Camera camera = this.getCamera();
camera.setX(Operators.lerp(camera.getX(), player.getX(), 0.1));
camera.setY(Operators.lerp(camera.getY(), player.getY(), 0.1));
Next
- Touching: walls, coins and enemies
- Maps with Tiled: whole levels to run and jump through
- Cat Platformer example: a complete platform game
-
Operators in the reference:
map,constrain,lerpand more