java粒子爱心特效代码
时间: 2024-01-17 13:18:31 浏览: 155
以下是一个使用Java实现的粒子爱心特效的代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ParticleHeartEffect extends JPanel implements ActionListener {
private Timer timer;
private Particle[] particles;
public ParticleHeartEffect() {
particles = new Particle[1000];
for (int i = 0; i < particles.length; i++) {
particles[i] = new Particle();
}
timer = new Timer(10, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
for (Particle particle : particles) {
g2d.fillOval((int) particle.x, (int) particle.y, 2, 2);
}
}
@Override
public void actionPerformed(ActionEvent e) {
for (Particle particle : particles) {
particle.update();
}
repaint();
}
private class Particle {
private double x;
private double y;
private double vx;
private double vy;
public Particle() {
x = ParticleHeartEffect.this.getWidth() / 2;
y = ParticleHeartEffect.this.getHeight() / 2;
double angle = Math.random() * 2 * Math.PI;
double speed = Math.random() * 2 + 1;
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
}
public void update() {
x += vx;
y += vy;
if (x < 0 || x > ParticleHeartEffect.this.getWidth() || y < 0 || y > ParticleHeartEffect.this.getHeight()) {
x = ParticleHeartEffect.this.getWidth() / 2;
y = ParticleHeartEffect.this.getHeight() / 2;
double angle = Math.random() * 2 * Math.PI;
double speed = Math.random() * 2 + 1;
vx = Math.cos(angle) * speed;
vy = Math.sin(angle) * speed;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Particle Heart Effect");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
ParticleHeartEffect particleHeartEffect = new ParticleHeartEffect();
frame.add(particleHeartEffect);
frame.setVisible(true);
}
}
```
这段代码使用Java的Swing库实现了一个粒子爱心特效。它创建了一个面板,并在面板上绘制了一些红色的小圆点,模拟了粒子的运动轨迹。通过定时器不断更新粒子的位置,实现了流动的爱心形状动画特效。
阅读全文