【发布时间】:2016-11-17 01:36:01
【问题描述】:
我正在尝试编写一个简单的弹跳球程序。它有一个矩形和两个球。球必须从矩形的墙壁上反弹(我已经成功编码)并且它们还必须相互反弹。这是我需要你帮助的地方。当我给球以相同的速度时,它们会很好地弹跳并且程序可以正常工作,但是我必须给球随机的速度。当我这样做时,球将不再弹跳,而是相互穿过。
import java.applet.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class BallApplet2 extends Applet implements Runnable
{
// Begin variabelen
int x_pos1 = 150;
int y_pos1 = 200;
int radius1 = 20;
int x_pos2 = 250;
int y_pos2 = 200;
int radius2 = 20;
private float ballspeedx1 = -3;
private float ballspeedy1 = 0;
private float ballspeedx2 = 3;
private float ballspeedy2 = 0;
public void init() {}
public void start() {
Thread th = new Thread (this);
th.start (); }
public void stop() {}
public void destroy() {}
public void run () {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
x_pos1 += ballspeedx1;
y_pos1 += ballspeedy1;
x_pos2 += ballspeedx2;
y_pos2 += ballspeedy2;
repaint();
// als x_pos < 100 is draait de richting van de bal om
if (x_pos1 < 100) {
ballspeedx1 = -ballspeedx1;
x_pos1 = 100;
}
if (x_pos2 < 100) {
ballspeedx2 = -ballspeedx2;
x_pos2 = 100;
}
// als x_pos > 300 is draait de richting van de bal om
if (x_pos1 > 300) {
ballspeedx1 = -ballspeedx1;
x_pos1 = 300;
}
if (x_pos2 > 300) {
ballspeedx2 = -ballspeedx2;
x_pos2 = 300;
}
// als de x van de rode bal gelijk is aan de x en twee keer de straal van de blauwe bal, draaien beide ballen om.
if (x_pos1 == x_pos2 + 40) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
// als de x van de blauwe bal gelijk is aan de x van de rode bal, draaien beide ballen om.
if (x_pos2 == x_pos1 ) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
// als de x en twee keer de straal van de rode bal gelijk is aan de x van de blauwe bal, draaien beide ballen om.
if (x_pos1 + 40 == x_pos2) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
// als de x en twee keer de straal
if (x_pos2 + 40 == x_pos1) {
ballspeedx1 = -ballspeedx1;
ballspeedx2 = -ballspeedx2;
}
try { Thread.sleep (20); }
catch (InterruptedException ex) {}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY); }}
public void paint (Graphics g) {
g.setColor (Color.red);
g.fillOval (x_pos1 - radius1, y_pos1 - radius1, 2 * radius1, 2 * radius1);
g.setColor (Color.blue);
g.fillOval (x_pos2 - radius2, y_pos2 - radius2, 2 * radius2, 2 * radius2);
g.setColor(Color.black);
g.drawLine(80,80,80,320); // lijn links
g.drawLine(320,80,320,320); // lijn rechts
g.drawLine(80,80,320,80); // lijn boven
g.drawLine(80,320,320,320); // lijn onder
}
// Einde eventmethoden
}
有人有解决办法吗?如果是这样,请尽量保持简单:)
【问题讨论】:
-
这种事情可能很棘手,你是在任何时候解决碰撞(物理地将球移出碰撞)还是仅仅解决速度
-
我猜是速度/速度使球的位置不匹配,即不会出现
x_pos2 == x_pos1。也许尝试通过Math.abs(x_pos2-x_pos1)< bdist进行比较(bdist是相对于速度/速度计算的) -
啊,是的,JScooby 是对的,您正在比较它们的中心是否发生碰撞,您似乎没有使用半径 1 和半径 2 进行碰撞检测
-
同意@JScoobyCed,但您可能应该通过
Math.sqrt((x_pos2-x_pos1)*(x_pos2-x_pos1)+(y_pos2-y_pos1)*(y_pos2-y_pos1)) < 2 * radius)测试中心是否太近(小于半径的2倍) -
顺便说一句,要进行逼真的弹跳,您可能应该做一些更复杂的数学运算。当两个球以任意角度相互撞击时,不能只反转 x 和 y 速度。