gpt4 book ai didi

java - boolean 键[]获取NPE(空指针表达式)java不知道如何在游戏开始时分配它?

转载 作者:行者123 更新时间:2023-12-01 18:37:21 26 4
gpt4 key购买 nike

这是主类,它扩展了另一个包含 gameloop() 的类。
keys() 在 gameloop() 内检查

private boolean keys[] ;
public void keyPressed(KeyEvent ke){
keys[ke.getKeyCode()] = true;
}

void keys(){

if(keys[KeyEvent.VK_Q] == true){ //NPE here (Null Pointer Expression)
stop();
}

if(keys[KeyEvent.VK_SPACE] == true && jump== false){
jump = true;
cjump = true;
jkptime = System.currentTimeMillis();
_7zl2m.setVY(-0.4f);
}

if(_7zl2m.getX() >= (bg.getWidth(null) - _7zl2m.getWidth()) && keys[KeyEvent.VK_RIGHT] == true || _7zl2m.getX() <= _7zl2m.getWidth() + 15 && keys[KeyEvent.VK_LEFT] == true || _7zl2m.getY() <= bg.getHeight(null) - 350 && keys[KeyEvent.VK_UP] == true || _7zl2m.getY() >= bg.getHeight(null) - 160 && keys[KeyEvent.VK_DOWN] == true){
if(keys[KeyEvent.VK_RIGHT] == true || keys[KeyEvent.VK_LEFT] == true){
_7zl2m.setVX(0.0f);
}else if(keys[KeyEvent.VK_UP] == true || keys[KeyEvent.VK_DOWN] == true){
_7zl2m.setVY(0.0f);
}
}else{
if(keys[KeyEvent.VK_RIGHT] == true && jump == false){
_7zl2m.setVX(0.2f);
}

else if(keys[KeyEvent.VK_LEFT] == true && jump == false){
_7zl2m.setVX(-0.2f);
}

if(keys[KeyEvent.VK_UP] == true && jump == false){
_7zl2m.setVY(-0.2f);
}

else if(keys[KeyEvent.VK_DOWN] == true && jump == false){
_7zl2m.setVY(0.2f);
}
}

if(keys[KeyEvent.VK_RIGHT] == false || keys[KeyEvent.VK_LEFT] == false){
_7zl2m.setVX(0.00f);
}else if (keys[KeyEvent.VK_UP] == false || keys[KeyEvent.VK_DOWN] == false ){
_7zl2m.setVY(0.0f);
}
}

//release a key
public void keyReleased(KeyEvent ke){
keys[ke.getKeyCode()] = false;
}

当然它会是空的,因为我还没有按任何键......但是如何解决这个问题。我已经尝试过尝试 block

最佳答案

您最好使用HashSet<Integer>在这里,因为您不知道所有按键都会被按下

像这样初始化

private Set<Integer> keys = new HashSet<Integer>() ;

向其添加值,例如

keys.add(someValue);

并检查

keys.contains(someValue);

发布时将其从 Set 中删除

keys.remove(someValue);

关于java - boolean 键[]获取NPE(空指针表达式)java不知道如何在游戏开始时分配它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21371308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com