i have implemented a side scroller in 2D with Java2D look this is my piece of code
each entity extends an abstract class that has this methods implemented
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public Rectangle[] getEntityRectangle(){ Rectangle rect = new Rectangle((int)(position.getPosX() - size.getHalfWidth()), (int)(position.getPosY() - size.getHalfHeigh()), size.getWidth(), size.getHeigh()); return new Rectangle[]{rect}; }
public boolean collidedWith(Entity other) { Rectangle[] ownRect = getEntityRectangle(); Rectangle[] otherRect = other.getEntityRectangle(); for (int i = 0; i < ownRect.length; i++) { for (int j = 0; j < otherRect.length; j++) { if(ownRect[i].intersects(otherRect[j])){ return true; } } } return false; } |
if u look the implementation of the intersects method of the rect class you will see that i just a check between the basic variables of the two rect to chek,
for my there are not difference between proiectiles and environments, both are Entity so use this method.
Just for optimize and control the collision i have one list that contain all the shot of the enemy versus the player
and i verify the collision hire between player and enemy shot
and i have another list that contain all the environment and ther i verify the collision between player and environment elements
finally i have one for the enemy and i use it to verify player proiectiles versus enemy and enemy to player collisions