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

2018/9/12

Need help with simplifying code beccause it causes errors.

Recorsi Recorsi

2018/9/12

#
Hello, I made an enemy that shoots two projectiles at intervals. Here is the code for that:
private void shootProjectiles()
    {
        firstShotTimer--;
        if (firstShotTimer <= 0)
        {
            getWorld().addObject(projectile1, getX(), getY());
            firstShotDone = true;
        }
        if (firstShotDone)
        {
            secondShotTimer--;
        }
        if (secondShotTimer <= 0)
        {
            getWorld().addObject(projectile2, getX(), getY());
        }
    }
The problem is that if the main actor gets hit by the first projectile (which removes the main actor) it causes an error, because the second projectile tries to turn towards the nonexisting main actor. Error message: "java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed." is there a way to fix this without losing the "turntowards" ability? Thanks :)
Super_Hippo Super_Hippo

2018/9/12

#
Before using turnTowards, check if the actor is in a world. You should not have different code for each projectile.
Recorsi Recorsi

2018/9/12

#
Super_Hippo wrote...
Before using turnTowards, check if the actor is in a world. You should not have different code for each projectile.
Thanks. How can i combine the code for the projectiles? Edit: now i have this:
if (getWorld() == null) return;
       turnTowards(spaceship.getX(), spaceship.getY());
it still doesn't work
Super_Hippo Super_Hippo

2018/9/12

#
You need to do
if (spaceship.getWorld() == null) return;
Simply use 'new Projectile()' if you don't need to have a reference. And you only need one timer which you reset when a projectile is added.
Recorsi Recorsi

2018/9/12

#
Thanks :)
You need to login to post a reply.