我正在编写一个小2D游戏。我实际上忙于跳跃功能。当我按向上箭头键时,我希望我的播放器跳转。我设法让他跳跃,但是至少有一秒的延迟。对于像左或右移动的其他动作,这种情况不存在。你知道它来自哪里吗?
跳转的代码在keyReaction方法中。
42
感谢您的帮助。
使用if:
的代码public class John<I> extends AbstractGame<I> {
//lists
List<ImageObject<I>> floor = new ArrayList<>();
//variables
double jumpHeight = 0;
//boolean
boolean jump = false;
//fix values
int blockHeight = 40;
int blockWidth = 40;
public John(double width, double height) {
//getPlayer()
super(new ImageObject<>("player.png", new Vertex(120, height - 200), new Vertex(0, 0)), width, height);
//floor objects
for(int i=0; i<getWidth(); i+=blockWidth)
floor.add(new ImageObject<>("brick.png", new Vertex(i, getHeight() - blockHeight)));
//add arrays to canvas
getGOss().add(floor);
}
@Override
public void doChecks() {
for(ImageObject<I> f:floor) {
//gravity
if(!(jump) && !(getPlayer().touches(f)))
getPlayer().getMotion().y++;
//stop y-motion on ground
if(getPlayer().touches(f)){
getPlayer().getPos().y = getHeight() - blockHeight - getPlayer().getHeight();
getPlayer().getMotion().y = 0;}
}
}
@Override
public boolean isStopped(){
return false;
}
@Override
public void keyReaction(KeyCode keycode){
switch (keycode) {
//move left
case LEFT_ARROW:
getPlayer().getMotion().x = -2;
break;
case VK_A:
getPlayer().getMotion().x = -2;
break;
//move right
case RIGHT_ARROW:
getPlayer().getMotion().x = 2;
break;
case VK_D:
getPlayer().getMotion().x = 2;
break;
//jump
case UP_ARROW:
jump = true;
if(jumpHeight < 100){
jumpHeight += 5;
getPlayer().getPos().y -=5;
} else if (jumpHeight < 200){
jumpHeight +=5;
getPlayer().getPos().y +=5;
}
break;
case VK_W:
break;
case SPACE:
break;
}
}
@Override
public void keyReactionReleased(KeyCode keycode){
switch (keycode) {
//move left
case LEFT_ARROW:
getPlayer().getMotion().x = 0;
break;
case VK_A:
getPlayer().getMotion().x = 0;
break;
//move right
case RIGHT_ARROW:
getPlayer().getMotion().x = 0;
break;
case VK_D:
getPlayer().getMotion().x = 0;
break;
//jump
case UP_ARROW:
jump = false;
jumpHeight = 0;
break;
case VK_W:
jump = false;
break;
case SPACE:
break;
}
}
//test main
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new SwingScreen(new John<>(1800, 600)));
f.pack();
f.setVisible(true);
}
}
没有if:
的代码case UP_ARROW:
if(jumpHeight < 20){
jumpHeight += 5;
getPlayer().getPos().y = -5;
} else if (jumpHeight < 40){
jumpHeight +=5;
getPlayer().getPos().y = 5;
}
break;
KeyReaction:
case UP_ARROW:
getPlayer().getPos().y = -5;
break;
答案 0 :(得分:2)
在你的跳跃高度法中你有
jump = true;
if(jumpHeight < 100){
jumpHeight += 5;
getPlayer().getPos().y -=5;
} else if (jumpHeight < 200){
jumpHeight +=5;
getPlayer().getPos().y +=5;
}
break;
在那里的第4行,你有一个 - = 5的pos。可能还有另一种方法可以防止ypos低于0.然后会发生什么变化,你按下向上箭头,它会被发送40次(200/5),最终跳跃高度大于200,然后玩家开始向上。