Prova questo codice che usa immagini
package collisionesemplice;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CollisioneSemplice {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new BackgroundPane());
frame.pack();
frame.setVisible(true);
frame.setSize(300, 500);
}
});
}
}
class BackgroundPane extends JPanel {
private BufferedImage bg;
private BufferedImage bg2;
private int yOffset = 0;
private int yDelta = 4; // velocità scorrimento
Timer timer;
//
public BackgroundPane() {
try {
// bg = ImageIO.read(new URL("http://www.java2s.com/style/download.png"));
File file= new File("meteorite_01.gif");
bg = ImageIO.read(file);
//file= new File("meteorite_02.gif");
file= new File("astronave.gif");
bg2 = ImageIO.read(file);
} catch (Exception ex) {
ex.printStackTrace();
}
timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
yOffset += yDelta; // muove l'oggetto
if (yOffset > getHeight()) {
yOffset = 0;
}
repaint();
}
});
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(bg.getWidth(),bg.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int bg2Y = 400;
int xPos = (getWidth() - bg.getWidth()) / 2;
int yPos = yOffset;
g2d.drawImage(bg, xPos, yPos, this);
g2d.drawImage(bg2, xPos , bg2Y, this); // meteoritr fisso
Rectangle r1 = new Rectangle(xPos,yOffset,bg.getHeight(),bg.getWidth());
Rectangle r2 = new Rectangle(xPos ,bg2Y+5,bg2.getHeight(),bg2.getWidth());
if (r1.intersects(r2)) {
// yOffset = 0;
timer.stop();
setBackground(Color.RED);
}
g2d.dispose();
}
}