I need to make an object move a specific distance when the right or left key button is pressed.
So when i push the right arrow key i need the object to move say 10 spaces, and only 10 spaces . so every time i push right it will only move 10 spaces.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // instance fields private int stepCount; private int direction; // in act or method it calls for moving boolean left = Greenfoot.isKeyDown( "left" ); boolean right = Greenfoot.isKeyDown( "right" ); if (direction == 0 ) // accepting direction { if ( left && ! right ) direction == - 1 ; if ( right && ! left ) direction == 1 ; } if (direction != 0 && stepCount != 10 ) // moving { setLocation(getX()+direction, getY()); stepCount++; } if (stepCount == 10 && ( ! left && ! right ) ) // resetting { direction = 0 ; stepCount = 0 ; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | private int stepCountUp; private int directionUp; public void Run() { boolean up = Greenfoot.isKeyDown( "up" ); boolean down = Greenfoot.isKeyDown( "down" ); if (directionUp != 0 && stepCountUp != 2 ) { if ( up && ! down ) directionUp = - 100 ; if ( down && ! up ) directionUp = 100 ; } if (directionUp != 0 && stepCountUp != 2 ) // moving { setLocation(getX(), getY()+directionUp); stepCountUp++; } if (stepCountUp == 2 && ( ! up && ! down ) ) // resetting { directionUp = 0 ; stepCountUp = 0 ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | // instance fields private int hDir; // horizontal direction field private int vDir; // vertical direction field private int stepCount; // the step counter // in act or method it calls boolean left = Greenfoot.isKeyDown( "left" ); boolean right = Greenfoot.isKeyDown( "right" ); boolean up = Greenfoot.isKeyDown( "up" ); boolean down = Greenfoot.isKeyDown( "down" ); if ( hDir == 0 && vDir == 0 ) // accepting direction { int dx = 0 ; int dy = 0 ; if (left) dx--; if (right) dx++; if (up) dy--; if (down) dy++; if ( dx * dy == 0 && dx + dy != 0 ) // discernible direction { hDir = dx; vdir = dy; } } if ( ( hDir != 0 || vDir != 0 ) && stepCount != 5 ) // moving { setLocation(getX()+hDir* 2 , getY()+vDir* 2 ); stepCount++; } if (stepCount == 5 && ( ! left && ! right && ! up && ! down ) ) // resetting { hDir = 0 ; vDir = 0 ; stepCount = 0 ; } |