我正在研究Java中的游戏项目原型,我遇到了线路问题"碰撞"。我尝试了许多不同的方法让它发挥作用。有人可以帮我吗?我刚刚用完了想法,检查了一些像Mathworld这样的网站,但是当我尝试将这个数学重做为代码时,它并没有真正起作用。
class Ball {
int x, y, radius, dx, dy;
Color BallColor;
public Ball(int x, int y, int radius, int dx, int dy, Color bColor) {
this.x = x;
this.y = y;
this.radius = radius;
this.dx = dx;
this.dy = dy;
BallColor = bColor;
}
}
public class ball_1 extends Applet implements Runnable, MouseListener, MouseMotionListener {
Ball ball1, ball2;
int x1, x2, y1, y2,r1;
int a, b;
String msg = "";
double c,d,e;
@Override
public void init() {
this.setSize(800, 800);
ball1 = new Ball(400, 70, 20, 4, 1, Color.green);
ball2 = new Ball(40, 70, 20, 4, 1, Color.black);
Thread t = new Thread(this);
t.start();
addMouseListener(this);
addMouseMotionListener(this);
Point p1 = new Point(x1,y1);
Point p2 = new Point(x2,y2);
}
@Override
public void paint(Graphics g) {
g.setColor(ball1.BallColor);
g.fillOval(ball1.x, ball1.y, ball1.radius, ball1.radius);
g.setColor(ball2.BallColor);
g.fillOval(ball2.x, ball2.y, ball2.radius, ball2.radius);
g.drawLine(x1, y1, x2, y2);
g.drawString(msg, 80, 80);
}
@Override
public void run() {
boolean run = true;
while (run) {
try {
displacementOperation(ball2);
lineCollision(ball1);
ballCollision(ball1);
ballCollision(ball2);
Thread.sleep(40);
repaint();
} catch (Exception e) {
}
if (ball1.x >= 780 || ball1.y <= 0) {
run = false;
msg = "game over";
}
if (ball1.y >= 780 || ball1.x <= 0) {
run = false;
msg = "game over";
}
}
}
public void displacementOperation(Ball ball) {
if (ball.y >= 780 || ball.y <= 0) {
ball.dy = -ball.dy;
}
if (ball.x >= 780 || ball.x <= 0) {
ball.dx = -ball.dx;
}
ball.y = ball.y - ball.dy;
ball.x = ball.x - ball.dx;
}
public void lineCollision(Ball ball) {
d = ((y2-y1)*(ball.radius) -(x2-x1)*(ball.radius) +x2*y1 -y2*x1)/((y2-y1)*(y2-y1))/2 + ((x2-x1)*(x2-x1))/2 ;
if (ball.radius <= d){
ball.dy = -ball.dy;
ball.dx = -ball.dx;
}
ball.y = ball.y - ball.dy;
ball.x = ball.x - ball.dx;
}
public void ballCollision(Ball ball) {
a = (ball2.y - ball1.y) * (ball2.y - ball1.y) + (ball2.x - ball1.x) * (ball2.x - ball1.x);
b = ((ball1.radius + 10) + (ball2.radius + 10)) / 2 * ((ball1.radius + 10) + (ball2.radius + 10)) / 2;
if (a <= b) {
ball.dy = -ball.dy;
ball.dx = -ball.dx;
}
ball.y = ball.y - ball.dy;
ball.x = ball.x - ball.dx;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
x1 = e.getX();
y1 = e.getY();
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
x2 = e.getX();
y2 = e.getY();
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
}