我正在尝试创建一个游戏,但不知道如何使用图像作为玩家控制的角色。我有一个类,使对象成为用户控制的对象,并且一切正常,问题是我必须将用户控制的角色作为矩形来进行定位和移动,因此它必须保持为矩形,这就是我搜索的位置出现短缺。基本上我想知道我是否可以将图像粘贴到我拥有的矩形上并将其粘在上面。这是我的角色类别:
class Flyer{
static int panelWidth = 2200;
static int panelHeight = 1800;
public static Rectangle flyer = new Rectangle(panelWidth / 2 - 100, panelHeight / 2 - 100, 20, 20);
public static Rectangle flyer2;
public static int vertical;
public int startingY = 0;
public int newY;
Flyer(){
super();
}
public void repaint(Graphics g) {
int panelWidth = 2200;
int panelHeight = 1800;
if (vertical == startingY) {
startingY = flyer.y;
g.setColor(Color.red);
g.fillRect(flyer.x, startingY, flyer.width, flyer.height);
} else {
newY = startingY + vertical;
g.setColor(Color.red);
g.fillRect(flyer.x, newY, flyer.width, flyer.height);
}
}
}
最佳答案
Graphics 类还有其他可以证明有用的方法,其Graphics API会告诉你的。其中有几个名为 drawImage(...)
的重载。
您的 Flyer 类可以保存 BufferedImage 字段,然后通过您已经使用的 x 和 y 字段将图像放置在所需的位置,例如通过 g.drawImage(myImage, x, y, null);
如果图像需要方向性,那么您可以让该类保存多个图像,并根据方向字段的状态选择正确的图像。
关于java - 如何在 Java 中将图像用作对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239188/