I am going into walls in my maze game when I press 2 directional keys simultaneously. When I only use one directional key, it's fine. This is the code of my Player class: My World is 30,30,20.
Is there anyway to fix this with my cell-like world set-up? Help greatly appreciated!
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.List;
public class Player extends Actor
{
private static final int EAST = 0;
private static final int SOUTH = 90;
private static final int WEST = 180;
private static final int NORTH = 270;
private static final int SIZE = 20;
private boolean canMove;
private int dx;
private int dy;
public Player()
{
GreenfootImage img = new GreenfootImage(SIZE,SIZE);
img.setColor(Color.WHITE);
img.fill();
setImage(img);
dx = 0;
dy = 0;
}
public void act()
{
movement();
wallInteraction();
}
private void movement()
{
if(Greenfoot.isKeyDown("up")&&!facingUpWall()){
setRotation(NORTH);
move(1);
dx = 0;
dy = -1;
}
if(Greenfoot.isKeyDown("right")&&!facingRightWall()){
setRotation(EAST);
move(1);
dx = 1;
dy = 0;
}
if(Greenfoot.isKeyDown("left")&&!facingLeftWall()){
setRotation(WEST);
move(1);
dx = -1;
dy = 0;
}
if(Greenfoot.isKeyDown("down")&&!facingDownWall()){
setRotation(SOUTH);
move(1);
dx = 0;
dy = 1;
}
}
private void wallInteraction()
{
Wall w = (Wall)getOneObjectAtOffset(dx,dy,Wall.class);
if(w!=null){
Color theColor = w.getMyColor();
List<Wall> maze = getWorld().getObjects(Wall.class);
for(Wall part:maze){
if(part.getMyColor().equals(theColor)){
part.show();
}
}
}
}
private boolean facingUpWall()
{
int xOffset=0, yOffset=0;
switch( getRotation() ) {
case NORTH: yOffset=-1; break;
}
Actor wall = getOneObjectAtOffset(xOffset,yOffset,Wall.class);
return wall != null;
}
private boolean facingRightWall()
{
int xOffset=0, yOffset=0;
switch( getRotation() ) {
case EAST: xOffset=1; break;
}
Actor wall = getOneObjectAtOffset(xOffset,yOffset,Wall.class);
return wall != null;
}
private boolean facingLeftWall()
{
int xOffset=0, yOffset=0;
switch( getRotation() ) {
case WEST: xOffset=-1; break;
}
Actor wall = getOneObjectAtOffset(xOffset,yOffset,Wall.class);
return wall != null;
}
private boolean facingDownWall()
{
int xOffset=0, yOffset=0;
switch( getRotation() ) {
case SOUTH: yOffset=1; break;
}
Actor wall = getOneObjectAtOffset(xOffset,yOffset,Wall.class);
return wall != null;
}
}