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

2014/5/5

Grabbing a boolean from another Actor.

DennisDvD DennisDvD

2014/5/5

#
Hi all, I've been having problems with accessing a boolean from another actor. I followed a tutorial for accessing variables from another actor, I followed it and got no compile errors, but still it does not seem to work. Here is my code and what I'm trying to accomplish: The start of the class I'm trying to get the variables from ( called John ):
public class John extends Actor
{
    public boolean inCar = false;
The code in my Main (world) class:
public class Main extends World
{
    private John johnVariables;
    
    public Main()
    {    
        super(150, 150, 5); 
        johnVariables = new John();
        
        buildings();
        
        addObject ( new John(), 75, 125);
        
        addObject ( new House(), 115, 80);
        addObject ( new House(), 115, 125);
        
        addObject ( new Car(), 75, 50);
    }
    
    public John getVariables()
    {
        return johnVariables;
    }
And finally the code in my Car class, I'm trying to get the boolean in John's class in this class:
public void drive()
    {
        corners();
        Main mainWorld = (Main) getWorld();
        John john = mainWorld.getVariables();
        
        //John john = getOneIntersectingObject(John.class);
        if (john.inCar)
        {
            if (Greenfoot.isKeyDown("right")) turn(5);
            if (Greenfoot.isKeyDown("left")) turn(-5);
            if (Greenfoot.isKeyDown("up")) move(1);
        }
    }
Everything compiles, I get no errors when running, but I cant seem to "move" my car, because the boolean value never seems to be true (while it is true in John's class).
danpost danpost

2014/5/5

#
In your Main (world) class you do this: (1) Line 3 declares a John field named johnVariables; (2) Line 8 assigns the johnVariables field a value (a John object) returned fromr 'new John()' ; (3) Lines 20 through 23, you have a 'get' method that returns the value which is stored in the johnVariables field; All these things listed above are all fine and good, however line 12 adds an actor into the world; that actor being that which is returned from 'new John()', not the actor stored in the johnVariables field. They are two separate John objects. You need to add the actor stored in the johnVariables field into the world, not a different John object. Change line 12 to:
addObject(johnVariables, 75, 125);
DennisDvD DennisDvD

2014/5/5

#
Thanks so much Dan, it worked :) Appreciate your help!
You need to login to post a reply.