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

2023/5/9

Bullet despawn

Wizzzarium Wizzzarium

2023/5/9

#
How do I code this: A Bullet collides with another Object and the Object dissapears and the Bullet dissapears too so that It doesnt collete more Objects.
danpost danpost

2023/5/9

#
Wizzzarium wrote...
How do I code this: A Bullet collides with another Object and the Object dissapears and the Bullet dissapears too so that It doesnt collete more Objects.
What have you tried? Show attempted codes and explain how it is not what you want.
Deepfist Deepfist

2023/5/9

#
You need to implement a hit registration, you can do this the following way
public void act() {
      if (Remove())
    {
          getWorld().removeObject(this);
    }
}
public boolean Remove() {
       Object obj= (Object)getOneIntersectingObject(Object.class);
       if(obj != null)
        {
           return true;
           getWorld().removeObject(obj);
        }
       return false;
    }
In this instance the bullet is looking if it intersecting with the actor Object. If it isn't intersecting (so it is null or == null), then it returns false. this means that the bullet doesn't despawn when being created. If it is intersecting (so it is not null or != null), then the bullet returns true. This means that the if statement can continue and that the bullet can remove itself. When obj != null, then it will also remove the object it is touching with getWorld().removeObject(obj); If you want the object to remove itself instead of having the bullet remove the object, then instead of writing "getWorld().removeObject(obj);" you need to write a code which activates a boolean in the Object.class. Let's call this boolean "Hit", so in Object you put: public boolean Hit = false; Instead of getWorld().removeObject(obj); you write obj.Hit = true; In the act method of the Object.class you put
import greenfoot.*; 
public class Object extends Actor {
public boolean Hit = false;
public void act() {
          if(Hit == true) 
       {
          getWorld().removeObject(this);
          Hit = false;
       }
}
}
Hope this helps and that it works for you :D
You need to login to post a reply.