Jumping (the most basic platforming mechanic)
For coding jumping, do I simply use the max
function? Will that work alone?
player = object
x = 0
y = 0
vy = 7
health = 3
end
updateplayer = function()
if keyboard.UP or gamepad.LEFT_STICK_UP then
player.y = max(0,player.y + player.vy)
end
end
If you want typical platformer physics, then there is a method I usually use:
The player has a position (x and y) and a velocity (vx and vy). Every frame:
- Change the player's x by the player's vx.
- If the player is hitting a wall, move the player back and set the vx to 0.
- Change the player's y by the player's vy.
- If the player is hitting a wall:
- Move the player back and set the vy to 0.
- Keep track of whether the player has hit the ground.
- If the jump button is pressed and the player has hit the ground, set the player's vy to the jump velocity.
- Change the player's vx by the input X axis (such as
keyboard.RIGHT - keyboard.LEFT
)
For premade physics, you can use Quick Engine or Matter.js.
While I like this method [because it is the smarter approach], I just think I want to stick to the max
function. Will that alone do it?
If the player presses up, they will fly upwards at 7 pixels per frame until up is released. They will also teleport to y=0 if their Y position is below 0. If you want to use this approach, you may need a timer to stop the player from flying up some time after leaving the ground.