I've had some issues with wall collisions in my. Could someone please tell me how to improve it?
Click here to go to the game.
int dx=0, dy=0;
if (Greenfoot.isKeyDown("right")) dx++;
if (Greenfoot.isKeyDown("left")) dx--;
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
if (dx!=0 || dy!=0)
{
setLocation(getX()+dx, getY()+dy);
if (isTouching(Box.class)) setLocation(getX()-dx, getY()-dy);
}int dx=0, dy=0;
if (Greenfoot.isKeyDown("right")) dx++;
if (Greenfoot.isKeyDown("left")) dx--;
if (Greenfoot.isKeyDown("up")) dy--;
if (Greenfoot.isKeyDown("down")) dy++;
if (dx!=0 || dy!=0)
{
setLocation(getX()+dx, getY()+dy);
if (isTouching(Box.class)) setLocation(getX()-dx, getY()-dy);
} double vspd, hspd, spd = 2;
public void act()
{
vspd = Boolean.compare(Greenfoot.isKeyDown("s"), Greenfoot.isKeyDown("w")) * spd;
hspd = Boolean.compare(Greenfoot.isKeyDown("d"), Greenfoot.isKeyDown("a")) * spd;
move();
}
private void move() {
List<Actor> walls = getObjectsInRange(40, Wall.class);
boolean canMove = true;
for(Actor wall : walls) {
double rightCheck = (wall.getX() - wall.getImage().getWidth()/2) - (getX() + getImage().getWidth()/2);
double leftCheck = (getX() - getImage().getWidth()/2) - (wall.getX() + wall.getImage().getWidth()/2);
double topCheck = (getY() - getImage().getHeight()/2) - (wall.getY() + wall.getImage().getHeight()/2);
double bottomCheck = (wall.getY() - wall.getImage().getHeight()/2) - (getY() + getImage().getHeight()/2);
if(hspd > 0 && topCheck < 0 && bottomCheck < 0 && leftCheck < 0) {
if(rightCheck - hspd < 0 && rightCheck != 0) hspd = Math.abs(rightCheck);
else if(rightCheck == 0) hspd = 0;
}
if(hspd < 0 && topCheck < 0 && bottomCheck < 0 && rightCheck < 0) {
if(leftCheck + hspd < 0 && leftCheck != 0) hspd = -Math.abs(leftCheck);
else if(leftCheck == 0) hspd = 0;
}
if(vspd < 0 && rightCheck < 0 && leftCheck < 0 && bottomCheck < 0) {
if(topCheck + vspd < 0 && topCheck != 0) vspd = -Math.abs(topCheck);
else if(topCheck == 0) vspd = 0;
}
if(vspd > 0 && rightCheck < 0 && leftCheck < 0 && topCheck < 0) {
if(bottomCheck - vspd < 0 && bottomCheck != 0) vspd = Math.abs(bottomCheck);
else if(bottomCheck == 0) vspd = 0;
}
}
if(canMove) setLocation(getX() + (int)hspd, getY() + (int)vspd);
}
}