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

2018/3/15

How to get a location from a class to another?

kronama kronama

2018/3/15

#
Hey, i wanna know how to o get a location ("X" and "Y")from a class to another but respecting encapsulation? I wanna get location of gamer.class and use it on monster.class but all my variables need to be private. Im using a method on gamer.class to get the X and Y position. And on monster.class im trying to get the values like this: X = getWorldOfType(gamer.class).getXmethod(); I got an ERROR: "Cannot cast MyWorld to actor"
kronama kronama

2018/3/15

#
plz danpost can you help?
danpost danpost

2018/3/15

#
You do not need any extra variables, private or otherwise. The Actor class already provides private 'int x' and 'int y' fields with public 'getX()' and getY()' methods to return the values of those private fields. All you need to do is get a reference to the gamer class object as, at minimum, an Actor object to execute those methods on. One way might be as follows:
1
2
3
4
5
6
7
if (!getWorld().getObjects(gamer.class).isEmpty()) // if a gamer object is in the world
{
    Actor actor = (Actor)getObjects(gamer.class).get(0); // get reference to gamer object
    int gamerX = actor.getX(); // get x of gamer object
    int gamerY = actor.getY(); // get y of gamer object
    // etc.
}
Please note that I do not refer to the gamer object as a gamer class. They are two totally distinct objects, each of a different Type -- one is a Class (extending Object); the other is a gamer (extending Actor, extending Object). The objects of type Class are the individual "pages" of code that describe objects using fields, constructors and methods. The gamer object is an object created via the gamer class constructor -- an instance of the class. Hence, we can see if an object is a gamer object using the following:
1
if (actor instanceof gamer)
It asks if 'actor', some Object object, was created by way of the gamer class or any class that extends the gamer class.
kronama kronama

2018/3/15

#
Thanks a lot its working!, what does the "get(0)"?
Yehuda Yehuda

2018/3/16

#
It gets the first Object in a (zero based) java.util.List.
You need to login to post a reply.