我刚开始编码,我学习并观看了一些教程,最终我决定开始在自己的小游戏中工作。现在的问题是,我在运行游戏时没有得到任何类型的键盘输入。我在游戏类和所有内容中添加了关键监听器,但我的玩家不会移动。我已经看过几次代码,但是找不到任何类型的按键输入的原因。我看了一个有关如何获取按键输入的教程,该教程对视频中的那个人有用,但对我不起作用。游戏将开始并显示“玩家”,但我无法移动它。
我试图将keyadapter和keyevent导入我的游戏类或更改类的名称,甚至复制了与教程中的家伙完全相同的代码。
package com.tutorial.main;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Hotkeys extends KeyAdapter{
private Handler handler;
public Hotkeys(Handler handler){
this.handler = handler;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
//System.out.println(key);
for(int i = 0; i < handler.object.size(); i++){
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player){
if(key == KeyEvent.VK_W) tempObject.setVelY(-5);
if(key == KeyEvent.VK_S) tempObject.setVelY(5);
if(key == KeyEvent.VK_A) tempObject.setVelX(5);
if(key == KeyEvent.VK_D) tempObject.setVelX(-5);
}
else if(tempObject.getID() == ID.Player2){
if(key == KeyEvent.VK_UP) tempObject.setVelY(-5);
if(key == KeyEvent.VK_DOWN) tempObject.setVelY(5);
if(key == KeyEvent.VK_RIGHT) tempObject.setVelX(5);
if(key == KeyEvent.VK_LEFT) tempObject.setVelX(-5);
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
for(int i = 0; i < handler.object.size(); i++) {
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player){
if(key == KeyEvent.VK_W) tempObject.setVelY(0);
if(key == KeyEvent.VK_S) tempObject.setVelY(0);
if(key == KeyEvent.VK_A) tempObject.setVelX(0);
if(key == KeyEvent.VK_D) tempObject.setVelX(0);
}
else if(tempObject.getID() == ID.Player2){
if(key == KeyEvent.VK_UP) tempObject.setVelY(0);
if(key == KeyEvent.VK_DOWN) tempObject.setVelY(0);
if(key == KeyEvent.VK_RIGHT) tempObject.setVelX(0);
if(key == KeyEvent.VK_LEFT) tempObject.setVelX(0);
}
}
}
}
当我按w,a,s,d或向上,向下,向右,向左箭头时,我需要“玩家”移动