My question is, how can I get my move()
methods to work using KeyEvents
i.e. KeyEvent.VK_DOWN
?
I'm currently trying to use the import java.awt.event.KeyEvent;
in which I'll be using the arrow keys NOT numpad keys to move a player in a 2 dimensional grid. I have my actions moveUp();
moveRight();
moveDown();
and moveLeft();
in my super class User
and the class Player extends User
and contains the key event method. When I use the arrow keys the actor simply does not move, however when I manually click on the actor in the grid and select a method it will move. Therefore my move methods work, so I'm assuming my KeyEvent setup is broken. Pictures showing me manually controlling the methods are supplied.
User which contains the move methods
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 class contains 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();
}
}
}
Main class
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();
}
}