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

2019/11/24

Getting the location of an object

ihjufaeshiju ihjufaeshiju

2019/11/24

#
I am trying to get the location of every House object in the world. When I try:
getObjectsInRange(10, House.class)
The output is as follows:
[House@7fc57555, House@96c2d1c, House@3e805312, House@4f231380, House@1b6b1c9d, House@4f50bd78, House@27cfc3b5, House@452eaf12]
How can I get the X and Y coordinate of each of those objects?
danpost danpost

2019/11/24

#
ihjufaeshiju wrote...
I am trying to get the location of every House object in the world.
The output you are showing is what you get when the toString method is executed on the House objects. (or on the List<Object> object). Individually, you can get their locations with:
for (Object obj : getObjectsInRange(10, House.class));
{
    Actor house = (Actor)obj;
    int houseX = house.getX();
    int houseY = house.getY();
    // use these coordinates here to do whatever for each house
}
If you want all locations collected together, then:
java.util.List houses = getObjectsInRange(10, House.class);
int[][] houseLocs = new int[houses.size()][2];
for (int i=0; i<houses.size(); i++)
{
    Actor house = (Actor)houses.get(i);
    houseLocs[i][0] = house.getX();
    houseLocs[i][1] = house.getY();
}
ihjufaeshiju ihjufaeshiju

2019/11/24

#
Thank you, that works nicely. Can you explain what line 5 does though?
danpost danpost

2019/11/25

#
ihjufaeshiju wrote...
Can you explain what line 5 does though?
LIne 5:
Actor house = (Actor)houses.get(i);
defines a variable that can reference an Actor object and assigns to it an object, from the houses List object at index i, cast as an Actor object ( (Actor) ).
You need to login to post a reply.