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

2016/5/13

Giving one Object another Object's coordinates

BloodMate BloodMate

2016/5/13

#
I'm trying to make the Object "Zombie" chase the object "Player", but yet i haven't been able to let the Zombie know the Player's coordinates. Both are subclasses of "Actor" and i don't have a piece of code regarding this transfer of two integers. ( I would have tried it with the method turnTowards( int xPlayer, int yPlayer), but like already mentioned, i don't even have xPlayer and yPlayer given for the zombie.... ) Can anyone plase help me?
SPower SPower

2016/5/13

#
There are multiple methods to do this, but this one is (I think) useful in learning and also a nice way to implement it (although it does require a bit more code than other possibilities). In order to access the player, you'll have to keep a reference to it in an instance variable. You create this instance variable in your subclass of World, like this:
private Player player;
Then, in your world's constructor, you initialize it and add it to the world:
player = new Player();
addObject(player, x, y); // x and y are your choice, of course.
Then, add a method to your world subclass that will give others access to this player:
public Player getPlayer()
{
    return player;
}
Now in your Zombie class, you're gonna want to get this Player object. For that, all you need to do is this:
MyWorld world = (MyWorld)getWorld(); // or, if your world subclass has a different name, replace 'MyWorld' with that name
Player player = world.getPlayer();
// then you can use player.getX() and player.getY() to get its coordinates
The reason for the first line is because getWorld returns an object of the class 'World', but the class World is written by the Greenfoot creators and doesn't have your method 'getPlayer' in it. Only your specific subclass of world has that, so you need to convert it into that 'version'. (This will crash if the zombie is not in that 'kind' of world, say, if it were in a world of class DifferentWorld, that is not a subclass of MyWorld). If some parts are vague, don't hesitate to ask.
BloodMate BloodMate

2016/5/13

#
Thanks, works perfactly fine! The only thing unclear is the line
private Player player;
what is it for?
SPower SPower

2016/5/13

#
It is to keep track of the player object. If you were to simply say,
addObject(new Player(), x,y);
It's much harder to get a hold of that object again. It is possible with some Greenfoot methods, but the way that objects are normally 'kept track of' is through instance variables.
You need to login to post a reply.