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

2013/11/21

Issue with collision script

penorzilla penorzilla

2013/11/21

#
I have a collision script that will prevent the player from being able to walk through obstacles on the world. Here is one of the 4 collision scripts, there is one for each direction.
    /**
     * Checks for an Obstacle on the west of player.
     */
    public boolean checkWestWalls()
    {
        int spriteWidth = getImage().getWidth();//Gets the width of the player.
        int xDistance = (int) (spriteWidth / -2);//Divides the width of the player by -2.
        
        Actor westWall = getOneObjectAtOffset(xDistance, 0, Obstacle.class);//Finds the closest obstacle within reach of the players x coordinates.
        
        if(westWall == null)
        {
            return false;
        }
        
        else
        {
            stopByWestWall(westWall);
            return true;
        }
    }
    
    /**
     * Moves away from the obstacle.
     */
    public void stopByWestWall(Actor westWall)
    {
        int wallWidth = westWall.getImage().getWidth();//Gets the width of the obstacle.
        int newX = westWall.getX() - (wallWidth + getImage().getWidth()) / -2;//Calculates where the player is in relation to the obstacle.
        setLocation(newX, getY());//Moves the player 5 pixels away from the obstacle.
    }
This works fine on every side, except for when you touch a corner. If you are walking north, towards the south-west corner, you will go into the object a little bit, then end up about 30 pixels west of the object, but same Y coordinates. Similar effects happen when you hit any corners. Here is a link to the full project, you can find the collision scripts in the Player.class. Dropbox Link for Project
Entity1037 Entity1037

2013/11/22

#
What you essentially want in a collision detection method is the ability to prevent the player from going into walls at all. This can be done by alligning the actor agenst the object if it touches it. It would also be better if you detect for actors at every cell in the area the actor is about to move into. This way, you can detect the actor first, and then move the player agenst the actor instead of letting the player move normally which could cause the player to move into it (if he's going fast enough) and glitch like you described. I made a completed scenario with good hit detection that uses this exact concept if you want an idea on what to do (just don't copy it exactly, because then you wont learn very much. http://www.greenfoot.org/scenarios/9172
You need to login to post a reply.