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

2015/4/3

Using Variable from another class

maddi64 maddi64

2015/4/3

#
I know this has been overdone but i'm still haven't found exactly what I needed. I have looked at the asteroid tutorial but it hasn't helped me. i have a class (Frog) which needs to access a boolean variable (direction) from another class (Log). How do i go about doing this? I have used the following code but it says in the Frog Class: cannot find symbol - method getDirection()
public class Log extends Actor
{
    public boolean direction = true; 

      public void act() 
    {
            if (direction = true) {
                direction = false;
            } 
            else {
                direction = true;
            }
    }    

public boolean getDirection() 
{  
    return direction;
} 








public class Frog extends Actor
{
    public void checkCollision()
    {
        int x=getX();
        int y=getY();
        
        Actor collided;
        
        collided = getOneIntersectingObject(Log.class);
        boolean direction = getWorld().getObjects(Log.class).getDirection();
        if (collided != null)
        {
            if (direction == true) {
                setLocation(x+3,y);
            }
            
            else {
                setLocation(x-3,y);
            }
        }
    }
}
danpost danpost

2015/4/4

#
Line 11 will never be executed. The 'if' condition at line 7 will always be 'true' because you are actually assigning 'true' to 'direction' within the 'if' conditional part of the statement itself (direction = true). To just compare the value of 'direction' to 'true, use the conditional equality symbol ('==') of a double equal sign (direction == true). Because 'direction' is a boolean value in itself, you can just use its value as the condition, 'if (direction)' or 'if (!direction)'. Furthermore, after correcting that, you will find that the logic of the 'act' method would say to set the value of 'direction' to false if it is currently true, otherwise set it to true (since it was false). This results in the value of 'direction' being in one state (either true or false) for all even act cycles and the other state on odd act cycles. I do not believe that this is the behavior you wanted. Next, in the Log class, line 37 tries to execute a 'getDirection' method on a List object. There is no 'getDirection' method in, or inherited to, the List class (a List object is what is returned by 'getObjects'). You probably wanted the 'direction' value of the 'collided' variable, if its value was not 'null'. However, you did not in any way indicate exactly what you were trying to get these actors to do while interacting with each other, I cannot help as far as getting them to do what you actually wanted.
You need to login to post a reply.