我在正在开发的游戏中旋转一个精灵时遇到了麻烦。我遵循了一个关于在 JPanels 上围绕图像中心旋转图像的教程(做得很好(。我什至创建了一个简单的项目,效果很好。
但是,当我尝试在游戏中使用相同的技术时,我的精灵不会旋转。我已经确定问题出在绘制精灵上,因为我通过println()
语句检查了paintComponent(Graphics g)
方法,旋转值已正确更新,并且在适当的时候调用了repaint()
方法。
以下是该问题的相关代码(不包括不必要的方法等(:
最高级别的班级:
public abstract class GameObject extends JPanel {
protected BufferedImage image;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw sprite
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0, 0, null);
// Clean up
g.dispose();
g2.dispose();
}
}
最低级别的班级:
// Entity is a subclass of GameObject.
// It does not override paintComponent.
// All it does is add an update method that is called every game tick.
public abstract class MicroObject extends Entity {
protected Location location; // variable to store position and rotation
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.translate(this.getWidth() / 2, this.getHeight() / 2);
g2.rotate(Math.toRadians(location.getRotation()));
// In the following two lines, image is inherited from GameObject
g2.translate(-image.getWidth(this) / 2, -image.getHeight(this) / 2);
g2.drawImage(image, 0, 0, null);
g2.dispose();
g.dispose();
}
}
我知道这不一定是一个独特的问题,但我查看了所有"重复"线程,它们都给我留下了相似的答案,但最终还是同样的问题。如果有人花时间查看我的代码并查看我出错的地方,我将不胜感激。
谢谢大家!
不要释放那些图形对象!它们被 Swing 重用来绘制子组件和边框。
它不起作用的原因是GameObject
在MicroObject
可以使用图形对象之前释放了图形对象。
此外,没有理由将图像绘制两次。删除GameObject
paintComponent()
中的代码。
最后,只使用类。这些没有理由是抽象的。
所以:
最高级别的班级:
public class GameObject extends JPanel {
protected BufferedImage image;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Don't draw sprite. Subclass will do that.
// Don't clean up. Swing does that for us.
}
}
最低级别的班级:
// Entity is a subclass of GameObject.
// It does not override paintComponent.
// All it does is add an update method that is called every game tick.
public class MicroObject extends Entity {
protected Location location; // variable to store position and rotation
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.translate(this.getWidth() / 2, this.getHeight() / 2);
g2.rotate(Math.toRadians(location.getRotation()));
// In the following two lines, image is inherited from GameObject
g2.translate(-image.getWidth(this) / 2, -image.getHeight(this) / 2);
g2.drawImage(image, 0, 0, null);
}
}