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.
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
/**
* 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.
}
