我的问题是,我怎样才能让我的move()
方法使用KeyEvents
ie KeyEvent.VK_DOWN
?我目前正在尝试使用import java.awt.event.KeyEvent;
我将使用箭头键而不是数字键盘键在二维网格中移动玩家。我有我的动作moveUp();
moveRight();
moveDown();
,moveLeft();
在我的超类User
和类Player extends User
中,包含关键事件方法。当我使用箭头键时,演员根本不会移动,但是当我手动单击网格中的演员并选择一种方法时,它将移动。因此我的移动方法有效,所以我假设我的 KeyEvent 设置已损坏。提供了显示我手动控制方法的图片。
包含移动方法的用户
package info.gridworld.actor;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;
public class User extends Actor {
private boolean isStopped = false;
public User()
{
setColor(null);
}
public void moveUp(){
moveTo(getLocation().getAdjacentLocation(Location.NORTH));
}
public void moveDown(){
moveTo(getLocation().getAdjacentLocation(Location.SOUTH));
}
public void moveLeft(){
moveTo(getLocation().getAdjacentLocation(Location.WEST));
}
public void moveRight(){
moveTo(getLocation().getAdjacentLocation(Location.EAST));
}
}
Player 类包含 KeyEvents
package game.classes;
import info.gridworld.actor.User;
import java.awt.event.KeyEvent;
public class Player extends User{
public Player(){
}
public void keyPressed(KeyEvent e){
int keys = e.getKeyCode();
if((keys == KeyEvent.VK_UP)){
moveUp();
}
else if((keys == KeyEvent.VK_DOWN)){
moveDown();
}
else if((keys == KeyEvent.VK_LEFT)){
moveLeft();
}
else if((keys == KeyEvent.VK_RIGHT)){
moveRight();
}
}
}
主班
package game.classes;
import info.gridworld.grid.*;
public class PlayerRunner{
private static GameGrid world = new GameGrid();
public static void main(String[] args)
{
Player player = new Player();
world.add(new Location(0, 0), player);
world.show();
}
}