我需要能够在他跳跃时移动我的角色。问题是我不希望角色以传统方式移动。他是方形的,当他在地上时应该像这样移动:
我不希望他在动画完成之前停止移动。但是当他同时跳跃和移动时,就没有这样的动画了。当他在空中时,这一举动变得经典。
我做了一些测试代码,我设法得到了我想要的角色在地面上的移动,而不是在空中正常的横向移动。
我应该首先向您展示我的模型(Booby 是角色的名字):
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();
现在,他可以左右移动,甚至可以跳跃。但是如果你在他跳跃的时候按右,它会停止跳跃并向右移动。
我想要的是,例如,当他在跳跃并且您按右时,它只会向右移动一次。因此,如果你一直按向右并在跳跃,它会慢慢向右移动。