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();
}
}
The World class actually has a keyPressed() method. You can just extend World and override this method. It will give you a string parameter to work with instead of a KeyEvent. Use javax.swing.KeyStroke.getKeyStroke(description).getKeyCode() to figure out which key was pressed. The source for the World class is her: https://github.com/parkr/GridWorld/blob https://github.com/parkr/GridWorld/blob/master/framework/info/gridworld/world/World.java aster/framework/info/gridworld/world/World.java
As for getting access to your Actor's methods, I would put a reference to an Actor in the World class. Then when you add the Actor you want to move to the world, you can just set it there. Then when you're dealing with the keystrokes you have access to the Actor you want to manipulate.