【发布时间】:2016-01-30 18:46:34
【问题描述】:
我正在尝试创建一个简单的面板,其中二维球上下弹跳。我无法让它工作,因为出于某种原因,我每秒不能多次调用 repaint 方法。设计基本上是有一个对象可以用move()的方法给予“冲动”。每次调用evaluatePosition 方法时,都会通过经过的时间、速度和加速度来计算当前位置。面板的代码是:
public class Display extends JPanel {
private MovableObject object = new MovableObject(new Ellipse2D.Double(5,5,50,50));
private static final int DELAY = 1000;
public Display(){
object.move(50,50);
Timer timer = new Timer(DELAY, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
object.evaluatePosition();
repaint();
}
});
timer.start();
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawOval((int)object.getPosition().getX(), (int)object.getPosition.getY()
(int)object.getShape().getWidth(), object.getShape().getHeight());
}
此代码适用于 DELAY=1000,但不适用于 DELAY=100 或 DELAY=10 等。我在这里阅读了一些示例代码,但在我看来它们都像我已经做过的一样。那么为什么我的代码不起作用?
编辑(2016-01-30): 由于这似乎确实是一个性能问题,这里是 MovableObject 的代码(我只是认为它无关紧要,你可能会明白为什么):
public class MovableObject {
// I would really like to use Shape instead of Ellipse2D so that
// objects of any shape can be created
private Ellipse2D.Double shape;
private Point position;
// Vector is my own class. I want to have some easy vector addition and
// multiplication and magnitude methods
private Vector velocity = new Vector(0, 0);
private Vector acceleration = new Vector(0, 0);
private Date lastEvaluation = new Date();
public MovableObject(Ellipse2D.Double objectShape){
shape = objectShape;
}
public void evaluatePosition(){
Date currentTime = new Date();
long deltaTInS = (currentTime.getTime()-lastEvaluation.getTime())/1000;
// s = s_0 + v*t + 0.5*a*t^2
position = new Point((int)position.getX()+ (int)(velocity.getX()*deltaTInS) + (int)(0.5*acceleration.getX()*deltaTInS*deltaTInS),
(int)position.getY()+ (int)(velocity.getY()*deltaTInS) + (int)(0.5*acceleration.getY()*deltaTInS*deltaTInS));
lastEvaluation = currentTime;
}
}
public void move(Vector vector){
velocity = velocity.add(vector);
evaluatePosition();
}
public Point getPosition(){
return position;
}
public Ellipse2D.Double getShape(){
return shape;
}
我的 move 方法不会改变位置而是改变速度。 请注意,我刚刚将形状对象从 Shape 更改为 Ellipse2D 以测试我的代码是否因为附加代码而出现性能问题。所以如果你认为这比它需要的更复杂:我实际上想增加一些复杂性,以便 MovableObject 可以具有任何形状子类的形状。我见过很多对我来说似乎更复杂且渲染速度更快的代码。所以我想知道这有什么问题(除了渲染椭圆有点过于复杂)。
【问题讨论】:
-
可能相关? pavelfatin.com/low-latency-painting-in-awt-and-swing可能是paint()本身太慢了。
-
MoveableObject是什么样的? -
@ToxicTeacakes 4500 objects @ approximately 25fps, 10, 000 objecst @ approximately 25fps - 这些都没有经过大规模优化,我首先要承认它们是过于简单的例子,但是......跨度>