我需要能夠移動我的角色,而他跳躍。事情是,我不希望角色以傳統的方式移動。他是正方形的,他應該將這樣的,當他在地上:移動,同時跳躍一個方形字符
我不想在動畫結束前他停止移動。但是當他同時跳躍和移動時,就沒有這樣的動畫。當他在空中時,這一舉動變得很經典。
我做了一個小小的測試代碼,我設法得到了我想要的角色在地面上移動的東西,而不是在空中正常的橫向移動。
我應該先告訴你我的模型(鰹鳥是角色的名稱):
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