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

2019/4/2

Actor not in world

Kofi11 Kofi11

2019/4/2

#
public class Enemy2 extends Enemy
{
    int timesHit=2;
    /**
     * Act - do whatever the Enemy2 wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        moveEnemy();
        removeEnemy();
        hitByProjectile();
    } 
    public void hitByProjectile()
    {
       Actor projectile = getOneIntersectingObject(Projectile.class);
       if (projectile != null)
       {
         getWorld().removeObject(projectile);
         timesHit--;
       }
       if (timesHit == 0)
       {
          getWorld().removeObject(this); 
       }
    }
}
I'm making a side-scrolling space invaders game and this error keeps showing up when the enemy touches the bottom of my world. The error says it happens on both line 20 and 24. It would be greatly appreciated if someone could help me with this.
RedMine360 RedMine360

2019/4/2

#
If removeEnemy() is also removing the Enemy than thats the problem. After it got removed by removeEnemy(), hitByProjectile() is starting but it is not there anymore. Possible soultion check if Enemy is on the field and only than it is possible to get hit.
public void act() 
    {
        moveEnemy();
        removeEnemy();
        if(getWorld().getObjects(Projectile.class).size() != 0)
        {
            hitByProjectile();
        }
    }   
danpost danpost

2019/4/2

#
RedMine360 wrote...
If removeEnemy() is also removing the Enemy than thats the problem. After it got removed by removeEnemy(), hitByProjectile() is starting but it is not there anymore. Possible soultion check if Enemy is on the field and only than it is possible to get hit. << Code Omitted >>
Sorry, but that is not a possible solution. In fact, it has the same failings as the initial issue -- a NullPointerException error will be thrown on line 5, here. You cannot call a method (getObjects, removeObject or any other World method) on the returned value of getWorld if that value is null. The check to perform at line 5 is therefore:
if (getWorld() != null)
You need to login to post a reply.