This site requires JavaScript, please enable it in your browser!
Greenfoot back
SP00F3R
SP00F3R wrote ...

2013/1/31

Collision detection help

SP00F3R SP00F3R

2013/1/31

#
I'm currently creating a top down shooter styled game and have started to add colision detection. I'm currently working on when the player shoots the enemy it is removed from the wold, and when the bullet hits the enemy the bullet is also removed from the enemy. I am able to make both of these work seperatly but I'm not able to combine the two to work consistantly together. I currently have three classes, a Player class, a Bullet class and an Enemy class, which I have not added collision detection to yet. I used the code below, stored in the enemy class, to detect when the bullet contacts the enemy and to delete when it does:
1
2
3
4
5
6
7
8
9
public  void bulletDetection()
    {
        Actor a = getOneIntersectingObject(Bullet.class);
                
        if(a != null)
        {
            getWorld().removeObject(a);
        }
    }
And this is the code, stored in the bullet class, used to remove the enemy when it is hit with a bullet:
1
2
3
4
5
6
7
8
9
     public void hitDetection()
    {
        Actor b = getOneIntersectingObject(Enemy.class);
         
        if(b != null)
        {
            getWorld().removeObject(b);
        }
}
davmac davmac

2013/1/31

#
Only one of those can fire. If you want a bullet hitting something to cause both the bullet and the thing that was hit to be removed from the world, you should do the check in only one place (either the Bullet class, or the Enemy class). Have it remove both objects. Be careful, after removing an object, not to do anything which relies on the object location or you'll get an exception. Example:
1
2
3
4
5
6
7
8
9
public void hitDetection() 
   
   Actor b = getOneIntersectingObject(Enemy.class); 
      
   if(b != null
   
       getWorld().removeObject(b);  
       getWorld().removeObject(this);
   
SP00F3R SP00F3R

2013/1/31

#
Thanks alot for the help, it's all sorted now. Regarding your last sentence, what did you mean by anything which relised on the object location...etc Many thanks. Edit: I'm now working on the collision between the player and the enemy, when the player collides with the enemy it doesnt overlap and it is removed from the world as it has 'crashed' and 'died'. Would I include that in the section of code above, or would I do it in the player class?
davmac davmac

2013/1/31

#
I mean you can't call methods which use the actors location, such as the collision checking and getX()/getY(), after you've removed 'this' actor from the world. More information here.
SP00F3R SP00F3R

2013/1/31

#
Oh ok, I think I understand. I don't think the actors that are being removed, the enemy and bullet, will require that. Thanks a lot for the help.
BatteryBot BatteryBot

2016/3/4

#
nee
You need to login to post a reply.