我正在制作一个Java游戏,当用户按下某些键时,精灵会朝那个方向移动,并且它会更改精灵以匹配用户输入的方向。
这是我正在使用的代码:
int x_posI = (int) x_pos;
int y_posI = (int) y_pos;
if (downPressed && leftPressed) {
g.drawImage(hero225, x_posI, y_posI, this);
spr270 = false;
} else if (downPressed && rightPressed) {
spr270 = false;
g.drawImage(hero135, x_posI, y_posI, this);
} else if (upPressed && rightPressed) {
spr270 = false;
g.drawImage(hero45, x_posI, y_posI, this);
} else if (upPressed && leftPressed) {
g.drawImage(hero315, x_posI, y_posI, this);
spr270 = false;
} else if (leftPressed == true) {
g.drawImage(hero270, x_posI, y_posI, this);
spr270 = true;
} else if (rightPressed == true) {
g.drawImage(hero90, x_posI, y_posI, this);
spr270 = false;
} else if (upPressed == true) {
g.drawImage(hero, x_posI, y_posI, this);
spr270 = false;
} else if (downPressed == true) {
g.drawImage(hero180, x_posI, y_posI, this);
spr270 = false;
}
else{
g.drawImage(hero, x_posI, y_posI, this);
}
if(spr270) {
g.drawImage(hero270, x_posI, y_posI, this);
}
当我按向左键时,会发生以下情况:
当我放手时,会发生这样的事情:
我怎样才能让角色保持面向左?
这是内部的paint(Graphics g)方法,对吗?
将易失性图像字段精灵添加到您的类中(“受保护的易失性图像精灵;”)。 将逻辑更改为:
int x_posI = (int) x_pos;
int y_posI = (int) y_pos;
if (downPressed && leftPressed) {
this.sprite = hero225;
} else if (downPressed && rightPressed) {
this.sprite = hero135;
} else if (upPressed && rightPressed) {
this.sprite = hero45;
} else if (upPressed && leftPressed) {
this.sprite = hero315;
} else if (leftPressed == true) {
this.sprite = hero270;
} else if (rightPressed == true) {
this.sprite = hero90;
} else if (upPressed == true) {
this.sprite = hero;
} else if (downPressed == true) {
this.sprite = hero180;
}
// this.sprite will contain value set on last "movement"
g.drawImage(this.sprite, x_posI, y_posI, this);