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

2015/2/8

getX(), getY() From Different Actor

FlamingWaters FlamingWaters

2015/2/8

#
So I have an enemy that tries to attack my main character: Jellie. It is supposed to follow Jellie by constantly facing it. However, I used Jellie.getX(), and Jellie.getY(), and I got the error message; "non-static method getX(), cannot be referenced from a static context." How would I go about getting Jellie's X and Y to the Baddie?
danpost danpost

2015/2/8

#
Jellie is the name of your class. It is not the name of any Actor created from the class. It is the TYPE of actor created from the class. A class (or TYPE) does not have a location within any world. The actors created from the class will have location coordinates when added into a world.
// the following line will error:
int jellieX = Jellie.getX();
// but these lines will not:
Jellie jellie = new Jellie;
addObject(jellie, 0, 0);
int jellieX = jellie.getX();
Here, line 4 creates a Jellie actor and assigns the object to a local variable names 'jellie'. 'Jellie' refers to the class (or TYPE) and 'jellie' refers to the actor created from the class. I will presume you only have one Jellie object in the world and it can be referenced from an actor class with the following:
if (! getWorld().getObjects(Jellie.class).isEmpty())
{
    Actor jellie = (Actor)getWorld().getObjects(Jellie.class).get(0);
    int jellieX = jellie.getX();
    // etc.
Here, line 1 ensures that a Jellie object IS in the world so that we do not try to get a non-existent element from the list on line 3.
FlamingWaters FlamingWaters

2015/2/9

#
Thanks!
You need to login to post a reply.