This site requires JavaScript, please enable it in your browser!
Greenfoot back
brandondamante
brandondamante wrote ...

2013/7/19

Greenfoot character moves through walls only horizontally?

brandondamante brandondamante

2013/7/19

#
I have a project where I need to create a simple game in the program, Greenfoot. I made a character that is not supposed to go through walls. The wall is completely solid and works fine when the character tries to move through it vertically. The problem arises when it tries to move horizontally, as it goes through, though it shakes up and down rapidly inside the wall. The prisoner also can go through doors horizontally (Which are supposed to be solid), so I'll post the methods for both here:
private void cannotGoThroughDoor(){
    if(this.isTouching(Door.class)){
        Actor door = getOneIntersectingObject(Door.class);
        int x = this.getX();
        int y = this.getY();
        if(x < door.getX()){
            this.setLocation(getX() - 5, y);
        }
        else if(x > door.getX()){
            this.setLocation(getX() + 5, y);
        }
        if(y < door.getY()){
            this.setLocation(x, getY() - 5);
        }
        else if(y > door.getY()){
            this.setLocation(x, getY() + 5);
        }
    }
}

private void cannotGoThroughWall(){
    if(this.isAtWall()){
        Actor wall = getOneIntersectingObject(Wall.class);
        int x = this.getX();
        int y = this.getY();
        if(x < wall.getX()){
            this.setLocation(getX() - 5, y);
        }
        else if(x > wall.getX()){
            this.setLocation(getX() + 5, y);
        }
        if(y < wall.getY()){
            this.setLocation(x, getY() - 5);
        }
        else if(y > wall.getY()){
            this.setLocation(x, getY() + 5);
        }
    }
}
The reason for each if statement that sets the location is so that it move back from whatever side it touched.
danpost danpost

2013/7/19

#
If you save in a local field (or fields) the original direction of movement, then check for intersecting object, then when intersection found, move back in the opposite direction to move back off the object. Also, using this way you do not needs all those checks.
You need to login to post a reply.