在下面的代码中,我设法使这两个矩形在JPanel
边界处反弹,但当它们碰撞时(弹性碰撞(,我无法使它们反弹。我认为actionPerformed
方法有问题(如果我错了,请纠正我(。我应该在代码中修复什么?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class box {
public static void main(String args[]) {
objectFrame frame = new objectFrame();
}
}
class objectFrame extends JFrame {
objectFrame() {
objectPanel panel = new objectPanel();
this.setSize(500, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.add(panel);
}
}
class objectPanel extends JPanel implements ActionListener {
private Timer t;
private int x, velx, x2, velx2;
private Rectangle r1, r2;
objectPanel() {
t = new Timer(5, this);
x = 100;
x2 = 400;
velx = 2;
velx2 = 2;
r1 = new Rectangle(x, 10, 50, 30);
r2 = new Rectangle(x2, 10, 50, 30);
t.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle r1 = new Rectangle(x, 10, 50, 30);
Rectangle r2 = new Rectangle(x2, 10, 50, 30);
g.setColor(Color.BLUE);
g.fillRect(x, 10, 50, 30);
g.setColor(Color.RED);
g.fillRect(x2, 10, 50, 30);
}
public void actionPerformed(ActionEvent e) {
if (x < 0 || x > 450 || r1.intersects(r2)) {
velx = -velx;
}
if (x2 < 0 || x2 > 450 || r1.intersects(r2)) {
velx2 = -velx2;
}
x += velx;
x2 -= velx2;
repaint();
}
}
我相信您没有模拟考虑碰撞对象的质量和方向的反弹行为。
你需要实现弹性碰撞背后的物理原理才能获得效果:https://en.wikipedia.org/wiki/Elastic_collision
有很多例子。这是我不久前实现的一个。https://github.com/gtiwari333/java-collision-detection-source-code.冲突逻辑取自https://gamedev.stackexchange.com/questions/20516/ball-collisions-sticking-together.