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

2019/1/15

How to use "Actor stone = (Actor)getWorld().getObjects(Stone.class).get(0) " for multiple Actors

lm_s lm_s

2019/1/15

#
Hey, I wrote a program and I need to get the X and Y Positions from up to 5 objects of the class "Stone". The function
Actor stone = (Actor)getWorld().getObjects(Stone.class).get(0); 
xPos = stone.getX(); 
yPos = stone.getY();
just works for one object. How can I make this work for more Objects?
danpost danpost

2019/1/15

#
lm_s wrote...
Hey, I wrote a program and I need to get the X and Y Positions from up to 5 objects of the class "Stone". The function << Code Omitted >> just works for one object. How can I make this work for more Objects?
java.util.List stones = getWorld().getObjects(Stone.class); // get a list of stones
int[][] xys = new int[stones.size()][2]; // create an array for location coordinates of all stones
for (int i=0; i<xys.length; i++) // for each set of coordinates to be gotten
{
    Actor stone = (Actor)stones.get(i); // get reference to a stone
    xys[i][0] = stone.getX(); // get x-coordinate of stone
    xys[i][1] = stone.getY(); // get y-coordinate of stone
}
You may not need to create an array -- it really depends on what you do with the coordinates. It may be as simple as this:
for (Object obj : getWorld().getObjects(Stone.class)) // for each stone in world
{
    Actor stone = (Actor)obj;
    int stoneX = stone.getX();
    int stoneY = stone.getY();
    // do whatever you do for this stone
}
lm_s lm_s

2019/1/16

#
Thank you for your answer! Both versions are working well.
You need to login to post a reply.