java - 使 Sprite 移动,需要 Sprite 停留在他第一次移动的位置

标签 java applet

我正在制作一个java游戏,当用户按下某些键时, Sprite 会朝那个方向移动,并且它会更改 Sprite 以匹配用户输入的方向。 如果您想查看当前游戏,请访问此网站:http://thetutspace.org/acropolis/beta/

这是我正在使用的代码:

    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);
    }

当我按向左键时,会发生以下情况: i.stack.imgur[dot]com/owT3z.png

当我放手时,这就是我发生的事情: i.stack.imgur.com/2Wrjr[点]png

我怎样才能让角色保持面向左?

最佳答案

这是内部的paint(Graphics g)方法,对吧?

将 volatile 图像字段 Sprite 添加到您的类中(“ protected volatile 图像 Sprite ;”)。 将逻辑更改为:

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);

关于java - 使 Sprite 移动,需要 Sprite 停留在他第一次移动的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6317524/

相关文章:

java - 使用 .cer 文件签署 .jar 文件

java - 相对于原点移动网格

java - 将日历日期转换为字符串?

java - 来自 Beam PTransform 的 IllegalMutationException

java - 如何将单独 jar 中的 JPA 实体聚合到单个持久性单元中?

java - 关闭后如何在 Firefox 3 中重新打开 Java 控制台

java - 如何使用elasticsearch java API编写多个评分函数?

具有基于表单的身份验证的 Java Applet 在 IE 上工作但在 Chrome 上失败

在 IE9 中加载/重新加载页面时,Java 小程序在 java7 中失败

java - 如何使 ActionEvent 和 KeyEvent 触发相同的操作?