如何使用箭头键保持对象移动? [英] How do I keep an object moving using arrow keys?
问题描述
我正在做蛇游戏,我希望一旦按下按键,蛇就可以连续运动.因此,我按下了下键,即使释放键,它也会继续移动.现在,它只是在按住键的同时移动.
I am making a snake game, and I want my snake to be moving continuously once a key is pressed. So, I press the down key, and it keeps moving even if the key is released. Right now, it just moves while the key is being held down.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
mySegment[0].moveSouth();
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
mySegment[0].moveNorth();
repaint();
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT){
mySegment[0].moveWest();
repaint();
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
mySegment[0].moveEast();
repaint();
}
for (int a = 0; a < 10; a++) {
if (myFruit[a].distance (mySegment[0].getX(), mySegment[0].getY())
<= 20) {
myFruit[a].hide();
}
}
"mySegment [0]"是蛇,"moveSouth"或任何方向只是将其在该方向上移动了5个像素
The "mySegment [0]" is the snake, and the "moveSouth" or whatever direction just moves it 5 pixels in that directin
推荐答案
如果您想让蛇保持运动,则需要某种游戏循环(如前所述).最简单的方法是使用一个包含当前方向的字段,然后根据输入进行设置.因此,这里有一些方法/类可以用来设置正确的方向/位置
If you want to keep the snake moving you need some kind of game-loop (as mentioned before). The easiest way is having a single field containing the current direction, and set it based on the input. So here are a few methods/classes you could use to set the correct direction/position
方向枚举
public enum Direction
{
NORTH, EAST, SOUTH, WEST;
public Direction oposite()
{
switch(this)
{
case NORTH: return SOUTH;
case SOUTH: return NORTH;
case EAST: return WEST;
case WEST: return EAST;
}
}
}
设置当前方向的方法. (假设存在一个名为"currentDirection"的字段,其中包含表示当前方向的枚举(方向))
The method to set the current direction. (This assumes there is a field named 'currentDirection' which contains an enum (Direction) representing the current direction)
public void setDirection(Direction newDirection)
{
if(currentDirection != newDirection.oposite())
currentDirection = newDirection;
}
这是您游戏循环中的某个位置(计时器或while循环,其中包括睡眠"调用以防止CPU阻塞)
This is somewhere in your game loop (either an timer, or a while loop including a 'sleep' call to prevent CPU hugging)
switch(currentDirection)
{
case NORTH: mySegment[0].moveNorth(); break;
case EAST: mySegment[0].moveEast(); break;
case SOUTH: mySegment[0].moveSouth(); break;
case WEST: mySegment[0].moveWest(); break;
}
repaint();
当然不用调用"mySegment [0] .moveNorth();"或keyEvent的actionHandler中的等价物,则应仅调用"setDirection();"使蛇移动.
And of course instead of calling 'mySegment[0].moveNorth();' or someting equalivant in the actionHandlers for the keyEvents, you should only call 'setDirection();' to make the snake move.
希望这对您有所帮助.
这篇关于如何使用箭头键保持对象移动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!