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

2022/3/2

Communicating actor to actor

Harrypotamus Harrypotamus

2022/3/2

#
Hi, I'm very new to this, I was wondering if there was some way I could get a public variable from an actor to use in a different actor? The specific example is that I want the X and Y values of a car (which is variables carX and carY, which are always set to the getX and getY of the car) so that I can set a cannon's X and Y to the car.
RcCookie RcCookie

2022/3/2

#
Example:
public class Car extends Actor {
    private Cannon cannon;

    public Car(Cannon cannon) {
        this.cannon = cannon;
    }

    public void act() {
        if(cannon.getWorld() != null)
            cannon.setLocation(getX(), getY());
    }
}
Now create a Car like this:
Cannon cannon = new Cannon();
Car car = new Car(cannon);
When added to a world this will make the cannon follow the car.
danpost danpost

2022/3/3

#
The above response if only good if the cannon is created before the car. If the cannon is created after the car AND if there is one, and only one, car in the world, then you can use this in the class of the cannon:
Actor car = null;
if (getWorld().getObjects(Car.class).size() > 0) car = (Actor) getWorld().getObjects(Car.class).get(0);
if (car != null)
{
    int carX = car.getX();
    int carY = car.getY();
    // etc.
}
Spock47 Spock47

2022/3/4

#
If the order of creation of car and cannon can be either way (car before cannon OR cannon before car), still a similar solution like the one RcCookie presented can be used, that works in any case (any number of cars/cannons in the world):
public class Cannon extends Actor {
    private Car car;
 
    public void setCar(Car car) {
        this.car = car;
    }
 
    public void act() {
        if (car != null) {
            setLocation(car.getX(), car.getY());
        }
    }
}
This will work for multiple cars in the world, too. It would work for multiple cannons on one car, too. Live long and prosper, Spock47
You need to login to post a reply.