I’m modifying the original move() method to add a collision check each time the player presses a button, this is reduced to:
- 1) Check collisions via .intersects() , as our custom class Tiles extends the Java Rectangle class, we can use this built-in method.
- 2) If collisions return true, call backToPreviousPosition(direction)
- 3) If backToPreviousPosition(direction) is called, return the player to the previous position, making that effectively can’t cross through walls.

move():
public void move(){
switch (direction){
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
//System.out.println("[MOVE()] RIGHT PRESSED");
x[0] = x[0] + UNIT_SIZE;
break;
}
checkCollisions();
// Update player location variables and repaint()
if (checkCollisions() == true){
backToPreviousPosition(direction);
}else{
playerLocX = x[0];
playerLocY = y[0];
}
repaint();
}
checkCollisions()
boolean checkCollisions(){
// both player and walls are rectangles, can use intersect()
System.out.println("Loading COLLISIONS");
for(int i=0; i<listOfWallTiles.size();i++){
int _wallX = (int)listOfWallTiles.get(i).tilePosition.getX();
int _wallY = (int)listOfWallTiles.get(i).tilePosition.getY();
if((x[0] == _wallX) && (y[0] == _wallY)) {
return true;
}
}
for(int i=0; i<listOfItemTiles.size();i++){
int _itemX = (int)listOfItemTiles.get(i).tilePosition.getX();
int _itemY = (int)listOfItemTiles.get(i).tilePosition.getY();
if((x[0] == _itemX) && (y[0] == _itemY)) {
isItemCollider(listOfItemTiles.get(i));
break;
}
}
return false;
}
- If the player intersects its coordinates with a Wall coordinate, return true, this will return the player to the original coordinates before the latest movement.
- If the player intersects its coordinates with an Item coordinate, call isItemCollider(Tile) with the type of collision we’ve found and break the loop.
- Else return false, there’s no collisions
isItemCollider()
boolean isItemCollider(Tile itemTile){
listOfItemTiles.remove(itemTile);
listOfOccupiedTilePositions.remove(itemTile.tilePosition);
return true;
}
- For the moment just remove the item from the item list, and remove it as well from the occupied positions list. This will be redrawn as null on the next repaint() loop so it will look like the item has been picked up when the player touches it.
Leave a Reply