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

2015/1/24

Stopping the hero get pass the edge but letting the other actors pass.

C.C.S C.C.S

2015/1/24

#
Really struggling with getting the hero to stop at the world edge. I have to codes but none work.
private void checkEdge()
    {
        if (getX() >= getWorld().getHeight())
        {
            setLocation(0, getY());
        }
    }
This is kind of working. What I lean is that if I go pass X=0 it still passes but if I go to X=960 it puts me at X=0. If I make getX() <= it blocks me on the X axis at 0. Now this code puts me at X=0 is I get pass the middel fo the world.
public boolean isAtEdge()
    {
        if (getX() <= getWorld().getHeight())
        {
            setLocation(0, getY());
            
        }
        return isAtEdge();
    }
This is another code I made using the API but it when I try to run the game it crashes Greenfoot. Any suggestions to stop the hero at the edge but letting everything else pass?
Super_Hippo Super_Hippo

2015/1/24

#
The reason why the second code crashes Greenfoot is, that at the end of the method you call the method again. So it will never end this circle. If you only want the hero to stop at the edge can be done like that.
//call this method somewhere at the end of the act method behind every moving action
public void stopAtEdge()
{
    if (getX() >= getWorld().getWidth()-1) setLocation(getWorld().getWidth()-1,getY());
    else if (getX <=0 ) setLocation(0,getY());
}
If you need a boolean to return, this can return the right boolean:
public boolean isAtEdge()
{
    if (getX() >= getWorld().getWidth()-1 || getX <=0 ) return true;
    return false;
}
C.C.S C.C.S

2015/1/24

#
Thanks this helped a lot. Now I also know how the return statement works so thanks.
You need to login to post a reply.