How do I add sprite collision?

I’m currently trying to make a 2d game. The game window is 720x660 pixels, and each sprite I have is 20x20 pixels, so the actual grid is 36x33 tiles.
The type of tile on the grid is stored in a 36x33 array.

I currently have these classes:

  • Player
  • Walls
    and I’m trying to add these classes:
  • Bullet
  • Enemy

Currently my walls are stored in an arraylist, and I loop through them, adding 20 to their x and y position every time and drawing it

For collision, I currently have a variable for grid coordinate X and grid coordinate Y, and if the space above/below/left/right of the player’s position in the map array is a wall, it won’t allow the player to move there.

Once I add bullets and enemies, I don’t think this type of collision will work because the enemies and bullets can travel in between tiles, so I can’t use grid coordinates anymore.

How can I detect if the player sprite has touched another sprite? Once it detects what sprite it touches I will have it do the appropriate action.

All the sprites have a hitbox of 20x20

Hi @Marfmamow,

I think that you need box collision in order to detect if your player sprite touch another sprite.

You can check this link for more information:

How would I use that for multiple walls at the same time? Could I make a function that loops through the arraylist of walls, and gets their position, and then in keyPressed(), add if statements so that if the player is not collided, the inputs work, else the inputs won’t work? Is it a good idea to loop through the arraylist of walls every time an enemy/player moves?

Do your enemies and bullets collide with the walls?

Are you talking about when the player collide with another enemy or just blocking it when close to a wall?

I think it might be necessary to do that for now. Then if it’s too slow you can optimize your code.

See this thread:

2 Likes