我需要能够移动我的角色,而他跳跃。事情是,我不希望角色以传统的方式移动。他是正方形的,他应该将这样的,当他在地上:移动,同时跳跃一个方形字符
我不想在动画结束前他停止移动。但是当他同时跳跃和移动时,就没有这样的动画。当他在空中时,这一举动变得很经典。
我做了一个小小的测试代码,我设法得到了我想要的角色在地面上移动的东西,而不是在空中正常的横向移动。
我应该先告诉你我的模型(鲣鸟是角色的名称):
public class Booby {
int posX;
int posY;
boolean movingRight;
boolean movingLeft;
Booby() {
posX = 0;
posY = 500;
}
int getPosX() {
return posX;
}
int getPosY() {
return posY;
}
void move(int x, int y) {
posX += x;
posY += y;
}
}
这里是我的控制器:
public class Controller extends KeyAdapter implements ActionListener {
Timer loop;
Booby booby;
boolean right;
boolean left;
boolean up;
int countUp = 0;
int jump = 0;
int countLeft = 0;
int countRight = 0;
Controller(Booby b, View v) {
booby = b;
loop = new Timer(0, this);
}
// Key events
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_UP:
up = true;
right = false;
left = false;
loop.start();
break;
case KeyEvent.VK_RIGHT:
right = true;
left = false;
up = false;
loop.start();
break;
case KeyEvent.VK_LEFT:
left = true;
up = false;
right = false;
loop.start();
break;
}
}
public void actionPerformed(ActionEvent evt) {
if (up) {
countUp++;
jump++;
// When UP is pressed, it moves up a bit 10 times...
if (countUp <= 100 && countUp > 0) {
booby.move(0, -1);
}
// ...Then it moves down a bit 10 times
else if (countUp > 100) {
if (jump <= 200) {
booby.move(0, 1);
} else if (jump > 200) {
loop.stop();
jump = 0;
countUp = 0;
}
}
}
// When Right is pressed, it moves a bit 10 times to the right
else if (right) {
booby.movingRight = true;
countRight++;
if (countRight <= 315) {
booby.move(1, 0);
} else {
countRight = 0;
loop.stop();
booby.movingRight = false;
}
}
// When Leftis pressed, it moves a bit 10 times to the left
else if (left) {
booby.movingLeft = true;
countLeft++;
if (countLeft <= 315) {
booby.move(-1, 0);
} else {
countLeft = 0;
loop.stop();
booby.movingLeft = false;
}
}
}
}
我也有一个JPanel持有的动画:
if (booby.movingRight) {
imgCharacter = new ImageIcon("images/booby_move_right.gif");
} else if (booby.movingLeft) {
imgCharacter = new ImageIcon("images/booby_move_left.gif");
} else {
imgCharacter = new ImageIcon("images/booby.png");
}
Image personnage = imgCharacter.getImage();
g.drawImage(personnage, booby.getPosX() * 1, booby.getPosY() * 1, null);
repaint();
现在,他可以向右,向左或甚至跳跃。但是如果你在跳跃时向右按,它会停止跳跃并向右移动。
我想要的是,当他跳起来,然后按右键时,它只会向右移动一次。因此,如果你继续按下并且你在跳跃,它会缓慢地向右移动。
+1为Bo鸟。好名字 。 – Raptor 2013-05-03 03:14:11