我正在尝试开发一个Java砖块破碎机(如DxBall)游戏,我想用自己的draw方法创建Ball对象。
我想要做的是:
public class Ball {
private int x, y, diameter;
public void Ball(){
x = 0;
y = 0;
diameter = 20;
}
public void draw(Graphics g){
g.setPaint(Color.red);
g.fillOval(x, y, diameter, diameter);
}
}因此,我的游戏引擎扩展了JFrame,它的paintComponent方法将调用游戏对象绘制方法。综上所述,用Java做面向对象的游戏合适吗?我的Ball类应该扩展什么?
发布于 2012-11-18 00:05:36
如果您希望使Ball成为图形组件,您可以扩展JComponent
public class Ball extends JComponent {
private int x;
private int y
private int diameter;
public Ball() {
x = 0;
y = 0;
diameter=20;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setPaint(Color.red);
g.fillOval(x, y, diameter, diameter);
}
}当您希望绘制组件而不是自定义draw方法时,只需调用repaint即可。
注意:构造函数没有返回类型。
发布于 2012-11-18 00:06:15
您的Ball类看起来还不错。它不需要扩展任何东西。您需要将Graphics对象从游戏对象的paintComponent传递给Ball draw方法。
发布于 2012-11-18 01:07:36
您的类很好,但我建议您扩展一个类。这个类通常称为Sprite、Action或GameObject,包含如下基本信息
image (or animation), position, collision rect and some basic functions like get and set it's position, speed and some collision detection functions if you wish.
一些资源。
希望他们能帮上忙。要绘制对象,请执行以下操作
g.drawImage(ball.image, ball.x, ball.y, null);https://stackoverflow.com/questions/13432231
复制相似问题