我正在研究java游戏。我的Background类需要宽度和高度,但仍然无法识别它们。
package TileMap;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import main.GamePanel;
public class Background {
private BufferedImage image;
private int width;
private double x;
private double y;
private double dx;
private double dy;
private double moveScale;
public Background(String s, double ms) {
try {
image = ImageIO.read(
getClass().getResourceAsStream(s)
);
width = image.getWidth();
height = image.getHeight();
moveScale = ms;
}
catch(Exception e) {
e.printStackTrace();
}
}
public void setPosition(double x, double y) {
this.x = (x * moveScale);
this.y = (y * moveScale);
fixPosition();
}
public void setVector(double dx, double dy) {
this.dx = dx;
this.dy = dy;
}
public void update() {
x += dx;
y += dy;
fixPosition();
}
private void fixPosition() {
while(x <= -width) x += width;
while(x >= width) x -= width;
while(y <= -height) y += height;
while(y >= height) y -= height;
}
public void draw(Graphics2D g) {
g.drawImage(image, (int)x, (int)y, null);
if(x < 0) {
g.drawImage(
image,
(int)x + GamePanel.WIDTH,
(int)y,
null
);
}
if(x > 0) {
g.drawImage(
image,
(int)x - GamePanel.WIDTH,
(int)y,
null
);
}
}
}
image.getHeight
给出了一个错误,说“高度无法解析为变量”,尽管image.getWidth
不是。有人可以告诉我我的代码有什么问题吗?
答案 0 :(得分:3)
您已定义width
但似乎没有定义height
变量(作为int)。这样做:
private int height;