I'm currently trying to code my first GUI game, where the player jumps from obstacle to obstacle. The player is supposed to do a simple jump when the space bar is pressed (without actually moving on the x axis), but when it's pressed, the player will only go up and not come down.
Here are the variables in my code:
private int playerY = 415, playerX = 100, score=0, maxHeight = 350;
private float speed=3, jumpStrength, weight=1;
Here is my code to make the player jump:
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE && playerY>=maxHeight) {
jumpStrength = 24;
playerY -= jumpStrength;
jumpStrength -= weight;
}
if (playerY>=maxHeight){
playerY = maxHeight;
}
}
public void keyTyped( KeyEvent e ) {}
public void keyReleased( KeyEvent e ){}
Does anyone have an idea on why it is not working and how I can fix it?
I don't know how the rest of your code looks or how your game works, but this is an Idea I have.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
jumpStrength = 24;
jumpStrength += weight;
playerY -= jumpStrength;
}
if (playerY>=maxHeight){
playerY = maxHeight;
}
}
public void keyTyped( KeyEvent e ) {}
public void keyReleased( KeyEvent e ){
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
jumpStrength = 24;
jumpStrength += weight;
playerY -= jumpStrength;
}
if (playerY<=0){
playerY = 0;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.