精灵的对角运动 [英] Diagonal movement of a sprite
本文介绍了精灵的对角运动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何实现对精灵的对角线运动?我创建了一个可移动的精灵(一个矩形),它可以在四个方向上移动.
How can I implement diagonal movement to a sprite? I created a movable sprite (a rectangle), which moves in four directions.
要对矩形进行动画处理,请使用计时器对象和执行动作的方法.我在keyPressed和keyReleased方法中实现了以下代码,以使其在四个方向上移动.
To animate the rectangle, a timer object and action performed method was used. I implemented the following code in keyPressed and keyReleased method to move it in four directions.
public void keyPressed(KeyEvent arg0){
int c=arg0.getKeyCode();
if(c==KeyEvent.VK_LEFT){
velx=-4;
vely=0;
}
else if(c==KeyEvent.VK_RIGHT){
velx=4;
vely=0;
}
else if(c==KeyEvent.VK_UP){
velx=0;
vely=-4;
}
else if(c==KeyEvent.VK_DOWN){
velx=0;
vely=4;
}
}
public void keyReleased(KeyEvent arg0){
velx=0;
vely=0;
}
推荐答案
以下是基于您的最后评论的代码:
Here is code based on your last comments:
// Set of currently pressed keys
private final Set<Integer> pressed = new TreeSet<Integer>();
@Override
public void keyPressed(KeyEvent arg0) {
int c = arg0.getKeyCode();
pressed.add(c);
if (pressed.size() > 1) {
Integer[] array = pressed.toArray(new Integer[] {});
if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_UP) {
velx = -4;
vely = -4;
} else if (array[0] == KeyEvent.VK_UP && array[1] == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 4;
} else if (array[0] == KeyEvent.VK_RIGHT && array[1] == KeyEvent.VK_DOWN) {
velx = 4;
vely = -4;
} else if (array[0] == KeyEvent.VK_LEFT && array[1] == KeyEvent.VK_DOWN) {
velx = -4;
vely = 4;
}
} else {
if (c == KeyEvent.VK_LEFT) {
velx = -4;
vely = 0;
} else if (c == KeyEvent.VK_RIGHT) {
velx = 4;
vely = 0;
} else if (c == KeyEvent.VK_UP) {
velx = 0;
vely = -4;
} else if (c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 4;
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
velx = 0;
vely = 0;
pressed.remove(Integer.valueOf(arg0.getKeyCode()));
}
这篇关于精灵的对角运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文