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

2017/12/11

HELP plz

I have made an object move when an arrow key is pressed. however I don't want the image to rotate. I have used this code: move(4); if(Greenfoot.isKeyDown("left")) { setRotation(180); } if(Greenfoot.isKeyDown("right")) { setRotation(0); } if(Greenfoot.isKeyDown("up")) { setRotation(-90); } if(Greenfoot.isKeyDown("down")) { setRotation(90); }
Super_Hippo Super_Hippo

2017/12/11

#
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++;
if (dx!=0 || dy!=0) setLocation(getX()+dx, getY()+dy);
danpost danpost

2017/12/11

#
The code Hippo provided is not quite the same as what you had while at the same time keeping the image from rotating. Your original code will have 4-way movement and is biased toward the last one being checked along each axis (right and down take priority). What Hippo provided is unbiased 8-way movement where the conditional check on the last line is optional (not really needed). For 4-way unbiased movement, change the condition on the last line to this:
if (dx*dy == 0)
which ensures that at least one of them is zero. Optionally, this could be used:
if (dx*dy == 0 && dx+dy != 0)
where the second condition also ensures that one is NOT zero (meaning one is and one is not).
You need to login to post a reply.