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

2012/10/10

Help with Location

CrazyCarl992 CrazyCarl992

2012/10/10

#
I have two actors in the world, a badger, and a truck. In the game the badgers are caught by a net and need to be located to the truck. The problem is the truck moves. How to I pass the trucks location to the badger? Currently I have the trucks getX() and getY() returns saved in a public variable, but when I try to use those variables, it comes out at the initalized zero. Help?
danpost danpost

2012/10/10

#
What are the name of your classes and in which class do you have to badger being netted?
CrazyCarl992 CrazyCarl992

2012/10/10

#
The classes are truck.class net.class and badger.class. The badger is netted with the badger class via a canSee command. The code has an if statement that says if the badger can see the net setLocation and now I need to pass the trucks current x and y to this function.
danpost danpost

2012/10/10

#
Use the following code
truck t = (truck) getWorld().getObjects(truck.class).get(0); // getting a reference to the truck
int truckX = t.getX(); // the x location of the truck
int truckY = t.getY(); // the y location of the truck
There must always be a truck in the world (if not you must check 'if (getWorld().getObjects(truck.class).isEmpty()) return;' before the code). If there is more than one truck, there is (currently) no way a determining which one is selected.
CrazyCarl992 CrazyCarl992

2012/10/11

#
Thank you very much! So what exactly is the code doing?
danpost danpost

2012/10/11

#
'getObjects(class)' is a World method that returns a List of Objects of the specified class. Since it is a World method, we must prefix it with 'getWorld()', which is an Actor method that returns the world that an actor is in. Since you are in the act (or a sub-method that it calls) in the badger class, it would be the world that the badger being netted is in. The prefix for 'getWorld()' in this case is understood (the 'this' keyword -- referring to the badger). Now that we have a list of 'truck' objects, we should make sure that the list is not empty. The 'isEmpty()' method of the List class can be used for that. If the list is not empty, the List method 'get(n)', will return the n'th item in the list (starting at zero). We cast the item to type 'truck' and assign that item to the new variable 't' that hold a 'truck' object. 't' can now be used as a prefix for public 'truck' class methods (as well as 'Actor' class methods, which 'getX()' and 'getY()' are) and public variables to perform some tasks and/or get information related to truck.
You need to login to post a reply.