I am having trouble trying to think of how I am going to approach collisions in my game. My idea which sucked in the beginning because it would reduce performance dramatically has failed which was when I was updating the list of walls it would check collision with players but the player would just stop and wouldn't be able to move anymore. Collision not only has to work with player but with at least 15-20 other entities in the game as well. Does anyone have a good idea to check collision with a top down shooter?
Here is my update method with everything being updated:
public void update(float dt){
inputHandler();
//Update the player
player.update(joystick1, joystick2, projectiles, dt);
updateCamera();
//Update them zombies
for(int i = 0; i < enemies.size(); i++){
Enemy e = enemies.get(i);
e.update(player, dt);
if(e.getDistanceFromPlayer() < 60){
//check collision
if(e.collided(player)){
player.hit(e, particles);
}
}
}
//Update Projectiles
for(int i = 0; i < projectiles.size(); i++){
Projectile p = projectiles.get(i);
p.update(dt);
//Check if projectile has hit any enemies
for(int j = 0; j < enemies.size(); j++){
Enemy e = enemies.get(j);
if(p.collided(e)){
p.remove();
e.hit(p);
ParticleEmitter.createBloodParticle(particles, e.getX(), e.getY(), 5, 500, 10);
}
}
}
//Update Items
for(int i = 0; i < items.size(); i++){
Item item = items.get(i);
if(item.collide(player)){
if(item instanceof Ammo){
player.getCurrentGun().addAmmo(item.getAmount());
}
if(item instanceof Health){
player.addHealth(item.getAmount());
if(player.getHealth() >= 100){
player.setHealth(100);
}
}
item.remove();
}
}
//Update them particles
for(int i = 0; i < particles.size(); i++){
Particle p = particles.get(i);
p.update(dt);
}
int numberOfObjectInGame = 1 + walls.size() + enemies.size() + items.size() + particles.size() + projectiles.size();
System.out.println(numberOfObjectInGame);
logger.log();
}
I don't know when to check for collisions. Should it be done in the update method or in the player update method, or at some other point? Really confused at this point.
EDIT:
Ok so added 4 rectangle bounds to my player and had each one checked to see if they have collided with a wall. So right now it is working but i'm pretty sure this is horribly inefficient. Any way to make this more efficient...
Here is the code:
for(int i = 0; i < walls.size(); i++){
Wall w = walls.get(i);
if(Intersector.overlaps(w.getBounds(), up)){
if(velocity.y < 0){
velocity.y = 0;
}
}
if(Intersector.overlaps(w.getBounds(), down)){
if(velocity.y > 0){
velocity.y = 0;
}
}
if(Intersector.overlaps(w.getBounds(), left)){
if(velocity.x < 0){
velocity.x = 0;
}
}
if(Intersector.overlaps(w.getBounds(), right)){
if(velocity.x > 0){
velocity.x = 0;
}
}
}
It is checked to see if the player is colliding with every wall and the problem is this is only the player. This has to check with every moving entity in the game. Is this a good way to implement this into a game or should I look into something else?