Reputation: 614
In my program I use key detection to move my player around. Although others have asked how to get working gravity, there is a very specific thing I would like to find out, how would I do this in real code from pseudocode.
if keys 1
pos[1] ++
unless you just jumped
Basically allowing me to take input from previous loops of my main game loop.
Upvotes: 1
Views: 102
Reputation: 608
There are a couple of ways you could do this.
1.) You could use global state to track a keypress boolean. Check it is "false" before jump, set it to "true" on jump, set it back to "false" on landing. Some games allow double-jumping, hence you would increment and decrement a keypress counter instead.
global has_jumped = False
if keys 1 and has_jumped is False:
pos[1] ++
has_jumped is True
// Apply gravity here.
if pos[1] <= 0: // Presumes ground is at Y = 0
has_jumped is False
2.) Alternatively, a more robust way to do this is to calculate if the player is standing on the map and use that to decide if the character can jump.
global player_acceleration_y = -10 // Gravity, in delta pixels per loop
global player_velocity_y = 0 // Velocity in pixels per loop
function loop():
pos[1] += player_velocity_y
player_velocity_y += player_acceleration_y
if pos[1] <= 0: // Just using a ground plane of 0 here. You could use more complex collision logic here.
pos[1] = 0 // Make sure we don't fall through the floor.
player_velocity_y = 0 // Stop falling.
if keys 1: // Jump
if pos[1] <= 0:
player_velocity_y = 30 // Jump up at a rate of 30 pixels per loop, which will be offset by gravity over time.
Upvotes: 2