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

2024/10/10

Getting an actor's coordinates in world class

tiny tiny

2024/10/10

#
So I have an actor moving and I want to get the x and y coordinates of that actor in the world class so I can store it in a variable inside the world class Basically I want to move a variable from an actor class to the world class in short terms Can someone help me please?
danpost danpost

2024/10/11

#
tiny wrote...
So I have an actor moving and I want to get the x and y coordinates of that actor in the world class so I can store it in a variable inside the world class
By keeping a reference to that actor in your World subclass, you can easily use something like the following:
private Player player = new Player();

public void act() {
    // ...
    int playerX = player.getX();
    // ...
}
Line 1 assigns an object of type Player to the field named "player". Actually, a memory address of the "player"'s information is stored and held by the field. As long as the field's given type is Actor (or Player, in this case), all Actor class public methods are accessible. To access public methods (and fields) in Player class, the field needs to be typed as Player (or the reference needs to be "typed" as Player when the method is accessed.. That would look like this:
private Actor player = new Player();

public void act() {
    // ...
    ((Player)player).superCharge(); // calls a method in Player class
    // ...
}
You need to login to post a reply.