Hi,
One thing that could be improved in the movement of the player is that when you press two keys at once, the player should do what the last key pressed did, rather than continuing to honour the old key press.
Here’s a class I used to take that into account, maybe it will be useful (This may help with your other problem too?):
import java.io.;
import java.util.;
import java.awt.event.*;
public class PlayersCurrentDirection{
// If empty, the player will not be trying to move
// The last pressed keys are first.
ArrayListSS<Integer> directionsPressed;
int direction;
public PlayersCurrentDirection(){
direction = DOWN;
directionsPressed = new ArrayListSS<Integer>();
}
public void stopMoving(){
directionsPressed.clear();
}
// this should really be called isTryingToMove, since it doesn't return whether or not the player is actually moving.
public boolean isMoving(){
return (directionsPressed.size() > 0 ? true : false);
}
public int getDirection(){
return direction;
}
public void applyKeyEvent(PlayerKeyEvent e){
if (e.getKeyEventType() == e.KEY_PRESS){
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A){
addDirection(LEFT);
}else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D){
addDirection(RIGHT);
}else if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W){
addDirection(UP);
}else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S){
addDirection(DOWN);
}
}else if (e.getKeyEventType() == e.KEY_RELEASE){
// Here we remove the key from directionsPressed if it is present.
// Note that we must remove all occurences, since there may be more
// than one of the same key press in the list if something weird happened.
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A){
removeDirection(LEFT);
}else if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D){
removeDirection(RIGHT);
}else if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_W){
removeDirection(UP);
}else if (e.getKeyCode() == KeyEvent.VK_DOWN || e.getKeyCode() == KeyEvent.VK_S){
removeDirection(DOWN);
}
}
}
protected void addDirection(int dir){
if (directionsPressed.size() == 0 || directionsPressed.get(0).intValue() != dir){
directionsPressed.add(dir);
direction = dir;
}
}
protected void removeDirection(int dir){
for (int i = 0; i < directionsPressed.size(); i++){
if (directionsPressed.get(i).intValue() == dir){
directionsPressed.remove(i);
i--;
}
}
if (directionsPressed.size() != 0){
direction = directionsPressed.get(0);
}
}
}