我想知道如何在两个圆圈之间发生碰撞。其中一个是可移动的,正如你所看到的,我想让它使可移动的圆圈实际上可以推动较小的圆圈。但是,我不希望简单的矩形碰撞。我试图使圆的推动方向取决于两个圆的位置。
package haex;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class haex extends Applet implements Runnable, KeyListener{
private static final long serialVersionUID = 1L;
int x = 0, y = 0, footballX = 100, footballY = 100;
double angle, xVel, yVel;
Image dbImage;
Graphics dbg;
boolean up, down, left, right, kick;
public void init(){
addKeyListener(this);
}
public void start(){
Thread th = new Thread(this);
th.start();
}
public void run(){
while(true){
angle = Math.atan2((footballX + 12) - (x + 25), (footballY + 12) - (y + 25));
if(Math.sqrt(Math.pow((footballX + 12) - (x + 25), 2) + Math.pow((footballY + 12) - (y + 25), 2)) <= 37){
xVel = Math.cos(angle);
yVel = Math.sin(angle);
footballX += xVel;
footballY += yVel;
}
if(up) y--;
if(down) y++;
if(left) x--;
if(right) x++;
try{Thread.sleep(1000/60);}catch(InterruptedException x){}
repaint();
}
}
public void stop(){}
public void destroy(){}
public void paint(Graphics g){
if(kick){
g.setColor(Color.lightGray);
}else{
g.setColor(Color.black);
}
g.fillOval(x, y, 50, 50);
g.setColor(Color.blue);
g.fillOval(x + 5, y + 5, 40, 40);
g.setColor(Color.black);
g.fillOval(footballX, footballY, 24, 24);
g.setColor(Color.white);
g.fillOval(footballX + 2, footballY + 2, 20, 20);
g.setColor(Color.black);
g.drawLine(x + 25, y + 25, footballX + 12, footballY + 12);
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP) up = true;
if(e.getKeyCode() == KeyEvent.VK_DOWN) down = true;
if(e.getKeyCode() == KeyEvent.VK_LEFT) left = true;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) right = true;
if(e.getKeyCode() == KeyEvent.VK_X) kick = true;
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP) up = false;
if(e.getKeyCode() == KeyEvent.VK_DOWN) down = false;
if(e.getKeyCode() == KeyEvent.VK_LEFT) left = false;
if(e.getKeyCode() == KeyEvent.VK_RIGHT) right = false;
if(e.getKeyCode() == KeyEvent.VK_X) kick = false;
}
public void update(Graphics g){
if(dbImage == null){
dbImage = createImage(this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
@Override
public void keyTyped(KeyEvent e){}
}
进行圆形碰撞应该比矩形更容易,只需为每个半径使用单个半径,而不是单独的 x 和 y 维度。只需计算它们的中心点之间的距离是否小于两者的半径即可。如果是这样,他们在触摸,如果没有,他们不是。
编辑:
所以问题是计算碰撞后球的合成速度和方向,而不是计算碰撞本身?如果您需要准确的帮助,请学会准确地解释问题。
在这种情况下,请比较两个中心点的 X 值和两个中心点的 Y 值。碰撞应该在很大程度上是弹性的,所以如果球被击中左侧,它应该去右侧,反之亦然。然后,您只需将 X 和 Y 分量组合成一个向量即可获得反应的方向和大小。