[英]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.