java流星雨特效代码
时间: 2023-11-12 22:57:59 浏览: 176
以下是一个简单的 Java 流星雨特效代码:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MeteorShower extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int NUM_METEORS = 20;
private static final int MAX_METEOR_SIZE = 20;
private static final int MAX_METEOR_SPEED = 10;
private static final int MAX_METEOR_TRAIL_LENGTH = 50;
private static final Color METEOR_COLOR = Color.WHITE;
private static final Color BACKGROUND_COLOR = Color.BLACK;
private Meteor[] meteors;
public MeteorShower() {
setBackground(BACKGROUND_COLOR);
meteors = new Meteor[NUM_METEORS];
Random rand = new Random();
for (int i = 0; i < NUM_METEORS; i++) {
int x = rand.nextInt(WIDTH);
int y = rand.nextInt(HEIGHT);
int size = rand.nextInt(MAX_METEOR_SIZE) + 1;
int speed = rand.nextInt(MAX_METEOR_SPEED) + 1;
int trailLength = rand.nextInt(MAX_METEOR_TRAIL_LENGTH) + 1;
meteors[i] = new Meteor(x, y, size, speed, trailLength);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (Meteor meteor : meteors) {
meteor.draw(g);
}
}
public void run() {
while (true) {
for (Meteor meteor : meteors) {
meteor.update();
}
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Meteor Shower");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
MeteorShower meteorShower = new MeteorShower();
frame.add(meteorShower);
frame.setVisible(true);
Thread thread = new Thread(meteorShower);
thread.start();
}
}
class Meteor {
private int x;
private int y;
private int size;
private int speed;
private int trailLength;
private int[] trailX;
private int[] trailY;
public Meteor(int x, int y, int size, int speed, int trailLength) {
this.x = x;
this.y = y;
this.size = size;
this.speed = speed;
this.trailLength = trailLength;
trailX = new int[trailLength];
trailY = new int[trailLength];
}
public void update() {
for (int i = trailLength - 1; i > 0; i--) {
trailX[i] = trailX[i - 1];
trailY[i] = trailY[i - 1];
}
trailX[0] = x;
trailY[0] = y;
x -= speed;
y += speed;
if (x < -size || y > MeteorShower.HEIGHT + size) {
Random rand = new Random();
x = MeteorShower.WIDTH + size;
y = rand.nextInt(MeteorShower.HEIGHT);
size = rand.nextInt(MeteorShower.MAX_METEOR_SIZE) + 1;
speed = rand.nextInt(MeteorShower.MAX_METEOR_SPEED) + 1;
trailLength = rand.nextInt(MeteorShower.MAX_METEOR_TRAIL_LENGTH) + 1;
trailX = new int[trailLength];
trailY = new int[trailLength];
}
}
public void draw(Graphics g) {
g.setColor(MeteorShower.METEOR_COLOR);
for (int i = 0; i < trailLength - 1; i++) {
g.drawLine(trailX[i], trailY[i], trailX[i + 1], trailY[i + 1]);
}
g.fillOval(x - size / 2, y - size / 2, size, size);
}
}
```
阅读全文