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

2017/3/12

Need help accessing variable from another class

timothytitus timothytitus

2017/3/12

#
Hi, i have a game where objects fall and there's a falling variable in the object class that changes to false after landing. The player is damaged when hit by a falling object. How do i access the object class from my player class to see whether the object is falling or not?
Super_Hippo Super_Hippo

2017/3/12

#
Let's rename the Object class to something else (for example Apple) to make it clear. You shouldn't name a class Object because there is already an Object class. Your player object does not want to get a variable from the Apple class, but from the Apple object.
//in Apple
private boolean falling;


public boolean isFalling() {return falling;}
//in Player's act method
Apple apple = (Apple) getOneIntersectingObject(Apple.class);
if (apple != null)
{
    if (apple.isFalling())
    {
        //take damage
    }
    else
    {
        //do nothing, or collect the apple
    }
}
timothytitus timothytitus

2017/3/12

#
Thanks I'll try
timothytitus timothytitus

2017/3/13

#
Hi it worked perfectly but I'm just wondering what's the difference between getOneIntersectingObject(Apple.class) and (Apple) getOneIntersectingObject(Apple.class). What does the (Apple) do?
danpost danpost

2017/3/13

#
The difference is the type of object that is being referenced (this is not the same as what type of object it actually is). Without (Apple), the reference is to an Actor object. As such, the 'isFalling' method will not be found when you call it on the referenced object because the method is in the Apple class, not the Actor class (or any class the Actor class extends from -- which is just the Object class).
timothytitus timothytitus

2017/3/13

#
Oh I see thanks
You need to login to post a reply.