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

2018/5/23

How do i turn an actor toward an other actor once?

Recorsi Recorsi

2018/5/23

#
Hello, i tried to make some sort of projectile that get directly aimed at the player when launched. But it should not follow the player constantly. I put this code in the constructor of the projectile class(because it should only be called once):
1
2
3
4
5
public void aim()
{
    Spaceship spaceship = (Spaceship)getWorld().getObjects(Spaceship.class);
    turnTowards(spaceship.getX(), spaceship.getY());
}
But somehow i get this error:
java.lang.NullPointerException at Projectile.aim(Projectile.java:26) at Projectile.<init>(Projectile.java:17)
What exactly is causing this, because the spaceship is in the world, aswell as the projectile and how do i fix this? Thanks :)
danpost danpost

2018/5/23

#
Recorsi wrote...
<< Error Omitted >> What exactly is causing this, because the spaceship is in the world, as well as the projectile
Actually -- no. This line in the error output:
at Projectile.<init>(Projectile.java:17)
tells me that the Projectile object is under construction and is not yet placed into any world. The getWorld method, therefore is returning a null value and thus the getObjects method cannot be called on it. Also, keep in mind that the getObjects method returns a List object and cannot be set to a variable that is to refer to a Spaceship object. Override the addedToWorld method of the Actor class and place the required code in it. The greenfoot framework will call it when the actor is added into any world. Refer to the Actor class API documentation for specifics on its use.
Recorsi Recorsi

2018/5/23

#
Now i got this(im not entirely sure if this is what you meant i should do) :
1
2
3
4
5
protected void addedToWorld(Spielfeld spielfeld)
{
    Spaceship spaceship = spielfeld.getSpaceship();
    turnTowards(spaceship.getX(), spaceship.getY());
}
In the world class i have this:
1
2
3
4
public Spaceship getSpaceship()
{
    return spaceship;
}
The errors are gone, but i cant get the code to work like it should.
danpost danpost

2018/5/23

#
Recorsi wrote...
Now i got this(im not entirely sure if this is what you meant i should do) : << Code Omitted >>
You cannot change the argument to your type of world, Spielfeld, in line 1. It must remain of type World. You can cast it to type Spielfeld within the method.
Recorsi Recorsi

2018/5/23

#
danpost wrote...
You cannot change the argument to your type of world, Spielfeld, in line 1. It must remain of type World. You can cast it to type Spielfeld within the method.
Thanks for your help it worked :)
You need to login to post a reply.