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

2020/11/6

Place reference into World

OfficialMajonaise OfficialMajonaise

2020/11/6

#
Im creating a game with exactly one player, and Im having issues with getting that player, so I want to place a reference into the World, so that I can do stuff like MyWorld.player.getX(); how would I do that?
danpost danpost

2020/11/6

#
OfficialMajonaise wrote...
Im creating a game with exactly one player, and Im having issues with getting that player, so I want to place a reference into the World, so that I can do stuff like MyWorld.player.getX();
A class does not contain an actor. It only describes an object. So, having a class reference an actor does not really make sense. A World object would contain actors. So, instead of "MyWorld", you might use "myWorld", where a specific World object is referenced. That is, "myWorld" is defined as
// in MyWorld class 
MyWorld myWorld = this;

// in Actor subclass (with an Actor instance that is in the world)
MyWorld myWorld = (MyWorld)getWorld();
Obviously, the code in MyWorld class is not really needed, as you can prefix with simply "this." in lieu of "myWorld." (after defining). So, in MyWorld, you might have:
// above constructor
private Player player;

// in constructor or prepare method
player = new Player();
addObject(player, 100, 100);

// method to get player
public Player getPlayer()
{
    return player;
}

// in act method
int playerX = player.getX(); // or
int playerX = this.player.getX(); // or
int playerX = getPlayer().getX(); // or
int playerX = this.getPlayer().getX();
In Actor subclass, you might use in some method (with actor in world):
int playerX = ((MyWorld)getWorld()).getPlayer().getX(); // or
int playerX = ((MyWorld)this.getWorld()).getPlayer().getX();
// or
MyWorld myWorld = (MyWorld)getWorld();
int playerX = myWorld.getPlayer().getX();
// or
MyWorld myWorld = (MyWorld)getWorld();
Player player= myWorld.getPlayer();
int playerX = player.getX();
// or any number of variants
OfficialMajonaise OfficialMajonaise

2020/11/7

#
Thanks alot man, it works :D
You need to login to post a reply.