import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
public class Ball {
static int x = 200;
static int y = 200;
static Random r = new Random();
static int velX = 5;
static int velY = 5;
public static int j;
public static int i;
public static int holy;
private static boolean collided = false;
public static void tick() {
x += velX;
y += velY;
if (x == 0) {
j++;
}
if (x == 680) {
i++;
}
if (y <= 0 || y >= 600 - 20)
velY *= -1;
if (x <= 0 || x >= 700 - 20)
velX *= -1;
collison();
}
public static void render(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, y, 20, 20);
}
private static void collison() {
if (collides()) {
velX *= -1;
velY *= -1;
}
}
public static boolean collides() {
collided = getBounds().intersects(Bar1.getBounds()) || getBounds().intersects(Bar2.getBounds());
return collided;
}
public static Rectangle okk() {
return new Rectangle(x, y, 1, 1);
}
public static Rectangle getBounds() {
return new Rectangle(x, y, 20, 20);
}
}
在collison方法中,如果collides方法返回true,我可以将velX和velY更改为负数。 有时collison方法无法正常工作,矩形的x和y会与其他矩形碰撞。 再次调用collison方法,并在它仍然发生碰撞时将其velX和velY更改为负(因为collison方法无法正确响应) 帮我解决这个问题