Reputation: 39
For the past week and a half, I have been programming a game from scratch with Java and Swing. So far, the game has been working smoothly except for one thing: jumping. I'm trying to implement parabolic jumping so that the player doesn't just teleport a little bit up. Instead, I want it to look realistic. My code so far looks like this(this is only the jump method, it calls it whenever the space, W, or up keys are pressed):
private void jump(Game game){
VectorF velocity = new VectorF(0f, 0.1f);
int t = 0;
while(t < 200){
if(checkTop(game)) break;
relPos.sub(velocity);
t++;
}
}
Upvotes: 0
Views: 1671
Reputation: 1143
Your game should have a game loop.
Typically, a (very basic) game loop looks like:
while (playing) {
accept_input()
update_game_logic()
render()
}
Within your update_game_logic()
function you would have a section which updates the player's position. The player's position update step will often look like some mixture of:
// 1. sum up 'effects' on the player
// think of 'effects' as velocities that we are adding together
// is jumping? add (0.0, 0.1),
// is holding the right-button? add (0.1, 0.0)
// 2. add a gravity effect (0.0, -0.05)?
// 3. sum up all velocity changes and apply them to the player
// 4. check for any collision and prevent it
// (straight up adjusting the position out of the colliding object will do for now, this will also stop you from falling through the floor due to gravity)
Because you are adjusting the player's position based on velocity every tick, you can continue to accept input and render the screen whilst updating the game logic.
Edit: If you want a proper parabolic arc, the 'effects' above should actually be forces which add together to cause a change in velocity (through acceleration) and then change the position in a more realistic fashion. View my similar answer here for more details.
Upvotes: 1