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

2018/8/22

Having trouble with using a counter

Alrightalright Alrightalright

2018/8/22

#
So what I'm doing is trying to make an object hover in the air. It is meant to move up and down around the same area. I want the object move in one direction till the counter hits 20, then move it the other direction for another 20 counts. And continue to do this for the duration of the game(level).
public void Ball()
{
    if(counter<20)
    {
        counter++;
        setLocation(getX(),getY()+1);
    }
    else if(counter>20)
    {
        counter++;
        setLocation(getX(),getY()-1);
    }
    else if(counter==40)
    {
        counter-=40;
        counter++;
    }
}
Here's my code. I've tried changing some lines up, like not doing the -40 at the end, and resetting the counter to 0, but once my object changes direction it doesn't change back. Thanks!
danpost danpost

2018/8/23

#
All possible values for the counter are exhaustd by line 8 -- that is, the 3rd if block will never by executed. You can just remove the "else" from line 13, however, that code, as is, is a bit much. Try the following:
public void Ball()
{
    counter++;
    if (counter < 20) setLocation(getX(), getY()+1); else setLocation(getX(), getY()-1);
    if (counter == 40) counter = 0;
}
Or, even shorter:
public void Ball()
{
    counter = (counter+1)%40;;
    setLocation(getX(), getY()+(counter < 20 ? 1 : -1));
}
You need to login to post a reply.