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

2018/11/22

I have a problem!... pls help me(infinity loop)

Felix123 Felix123

2018/11/22

#
I am a total beginner in java so please indulge me. So my problem is that i always have an infinity loop in the following code: public void Bewegen() { int x=0; int y=0; int gehen=5; while(gehen>0) { if(Greenfoot.isKeyDown("left")) { x=x-1; gehen--; } if(Greenfoot.isKeyDown("right")) { x=x+1; gehen--; } if(Greenfoot.isKeyDown("up")) { y=y-1; gehen--; } if(Greenfoot.isKeyDown("down")) { y=y+1; gehen--; } setLocation(x,y); } }
danpost danpost

2018/11/22

#
Felix123 wrote...
I am a total beginner in java so please indulge me. So my problem is that i always have an infinity loop in the following code: << Code Omitted >>
Actually, it is not an infinite loop. Pressing any arrow key at any time will break the loop; otherwise, it will indefinitely loop. What, exactly are you trying to achieve with this code? Is the actor supposed to move in steps of 5 cells (pixels?) at a time? or, what? As the code is written, the actor will always remain within 5 cells (pixels?) of the top-left corner of the world because x and y are absolute coordinates -- not offsets of the current location of the actor. Use:
1
setLocation(getX()+x, getY()+y);
to not have the actor hang near that corner.
Felix123 Felix123

2018/11/24

#
thx I want to achieve that the Actor can only move 5 cells.
Felix123 Felix123

2018/11/24

#
But why will the loop break if i press any key?
Super_Hippo Super_Hippo

2018/11/24

#
The loop breaks because the variable 'gehen' will be decreased by one. Then the loop is executed again immediately, the key is still pressed, it is decreased again... until it is 0 and the loop condition is not met anymore.
Felix123 Felix123

2018/11/24

#
OK do you have an idea how i could do it better?
Super_Hippo Super_Hippo

2018/11/24

#
You could take this one as a start:
1
2
3
4
5
6
int dx=0, dy=0;
if(Greenfoot.isKeyDown("left")) dx--;
if(Greenfoot.isKeyDown("right")) dx++;
if(Greenfoot.isKeyDown("up")) dy--;
if(Greenfoot.isKeyDown("down")) dy++;
setLocation(getX()+dx*5, getY()+dy*5);
Felix123 Felix123

2018/11/24

#
OK thx
You need to login to post a reply.