[英]How to make graphics appear at random and disappear on collision with another graphic?
我已经编写了一些有关移动图形(由矩形包围)的代码,并且尝试绘制另一个随机生成的椭圆形(矩形周围)。 现在,它正在快速生成WAY,我不想使用Thread.sleep; 因为它将停止监听键(据我所知?)。 擅长使用多线程的人也可以帮助我做到这一点,或者知道如何使图形显示直到被可移动图形触摸为止。
主类中的图形生成器:
public void paintComponent(Graphics g){
//System.out.println("X = " + al.x + ", Y = " + al.y);
boolean intersect = false;
int points = 0;
g.drawString("Points: " + points, 5, 445);
Rectangle r1 = new Rectangle(al.x, al.y, 10, 10);
g.setColor(Color.BLACK);
g.fillOval(al.x, al.y, 10, 10);
Random randX = new Random();
Random randY = new Random();
int xInt = randX.nextInt(590);
int yInt = randY.nextInt(440);
Rectangle dCoin = new Rectangle(xInt, yInt, 10, 10);
g.setColor(Color.YELLOW);
g.fillOval(xInt, yInt, 10, 10);
/*
* (???)
*
* for(int idx = 1; idx == 1; idx++){
* if(xInt < 590 && yInt < 440){
* }
* }
*
* Check if graphic collides with another:
*
* if(r1.intersects(r2)){
* doSomething;
* }
*
*/
repaint();
}
}
顺便说一句:r1围绕可移动图形,而r2是围绕随机生成的图形的矩形。 为了获得r1.intersects(r2)方法,我必须在椭圆周围制作一个不可见的矩形。
您应该使用Swing Timer
类在事件调度线程上定期生成ActionEvent
。 这避免了应用程序变得不响应按键和其他用户输入的问题。
actionPerformed
回调是路由中的钩子,用于移动和重绘要设置动画的对象。 在动画例程中,您可以记录自上次调用该方法以来经过的时间,以保持所需的速度。
Timer timer = new Timer(1000, new ActionListener() {
long lastTime = System.currentTimeMillis();
public void actionPerformed(ActionEvent evt) {
long timeNow = System.currentTimeMillis();
long timeEllapsed = timeNow - lastTime;
lastTime = timeNow;
if (timeEllapsed > 0L) {
for (Moveable mv : moveables) {
mv.updatePosition(timeEllapsed);
}
for (Drawable d : drawables) {
d.repaint();
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.