我对java很陌生,我正在努力实现一个pacman游戏,我使用一个图像初始化了一个幽灵,目前在我的游戏中使用了一个对象,但我希望有多个图像,所以我可以有不同的颜色鬼。但是当我初始化多个图像时,它只是重叠在另一个图像上。这是我如何初学Ghost
private Image RedGhost;
private Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down;
这里是我用来移动鬼的代码
private void moveGhosts(Graphics2D g2d) {
short i;
int pos;
int count;
for (i = 0; i < nrofghosts; i++) {
if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) {
pos = ghostx[i] / blocksize + nrofblocks * (int) (ghosty[i] / blocksize);
count = 0;
if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) {
dx[count] = -1;
dy[count] = 0;
count++;
}
if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) {
dx[count] = 0;
dy[count] = -1;
count++;
}
if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) {
dx[count] = 1;
dy[count] = 0;
count++;
}
if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) {
dx[count] = 0;
dy[count] = 1;
count++;
}
if (count == 0) {
if ((screendata[pos] & 15) == 15) {
ghostdx[i] = 0;
ghostdy[i] = 0;
} else {
ghostdx[i] = -ghostdx[i];
ghostdy[i] = -ghostdy[i];
}
} else {
count = (int) (Math.random() * count);
if (count > 3) {
count = 3;
}
ghostdx[i] = dx[count];
ghostdy[i] = dy[count];
}
}
ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
drawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1);
//drawblueGhost(g2d, ghostx[i] + 1, ghosty[i] + 1);
if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12)
&& pacmany > (ghosty[i] - 12) && pacmany < (ghosty[i] + 12)
&& ingame) {
dying = true;
}
}
}
总之,所有Ghost目前都是Red,我希望它是不同的颜色
答案 0 :(得分:2)
使用当前代码,您可以修改drawGhost方法,以获取正在绘制的重影颜色的标识符。然后你可以拥有另一个数组来保存每个ghost颜色的标识符。
但是,由于你使用Java,我建议利用OOP并创建一个Ghost类,它包含所有ghost的属性(x位置,y位置,颜色等)。然后,您可以拥有一组代表每个鬼魂的Ghost对象。
以下是一个例子:
创建一个Ghost类,它包含ghost可以拥有的所有属性:
public class Ghost {
private String color;
private int x;
private int y;
private boolean alive;
// getters and setters. You could even move the logic for moving a ghost to this class
...
}
然后你会像这样初始化鬼魂:
Ghost redGhost = new Ghost("Red");
Ghost greenGhost = new Ghost("Green");
Ghost pinkGhost = new Ghost("Pink");
您可以将它们存储在一个集合中:
Set<Ghost> ghostSet = new HashSet<Ghost>();
ghostSet.add(redGhost);
...
然后你的方法可以改为这样:
private void moveGhosts(Graphics2D g2d) {
// Utilize an enhanced for loop
for(Ghost ghost : ghosts){
...
...
ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]);
ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]);
drawGhost(g2d, ghost);
if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12)
...
...
}
}
现在,drawGhost方法将查看ghost类中的字段(通过调用getter和setter方法)来确定开始绘制的x和y。颜色字段用于确定要绘制的图像。