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

2016/1/7

Changing direction at world edge

hoothoot hoothoot

2016/1/7

#
My friend is coding a game and trying to get the objects to change directions as they hit the edge. why won't this code work?
public void act() 
    {
        
        if(isAtEdge() && edge==0)
            {
                
                edge=1;
            }
        if( isAtEdge() && edge==1)
            {
                
                edge=0;
            }
            if (edge==0)
            {
                move(6);
            }
            if (edge==1)
            {
                move(-6);
            }
        i++;
        hit();
        
    }    //I know its not supposed to be in the act method.
Super_Hippo Super_Hippo

2016/1/7

#
Change the 'if' in line 9 to an 'else if'. As it is right now, 'edge' will immediately change back to 0 when is set to 1. This should do the same (unless edge can be something different than 0 and 1).
if (isAtEdge())
{
    edge = (edge+1)%2;
}
move(6-12*edge);
If you use -1 and 1, it would be even easier:
if (isAtEdge())
{
    edge *= -1;
}
move(6*edge);
You need to login to post a reply.