我创建了一个弹跳球动画,该动画绘制在一个表面(我大学的图书馆)上,其中有2帧,还有2个阵列的球,其中一半进入第一帧,第二到第二帧。 由于某些原因-球穿过其框架的y和x轴。 我已经尝试过建议的某些解决方案(例如here),但没有帮助。.
我的代码:
public static void updateBalVelocity(Ball ball, int width, int height,
int minWidth, int minHeight) {
// get default value of the dx and dy
double dx = ball.getVelocity().getDx();
double dy = ball.getVelocity().getDy();
// check if the ball is touching the border (x/y axis) and if so -
// change it's directions
if ((ball.getX() + ball.getSize() + dx) >= width) {
dx = (dx > 0) ? -dx : dx;
} else if ((ball.getX() - ball.getSize()) <= minWidth) {
dx = Math.abs(dx);
}
if ((ball.getY() + ball.getSize() + dy) >= height) {
dy = (dy > 0) ? -dy : dy;
} else if ((ball.getY() - ball.getSize()) <= minHeight) {
dy = Math.abs(dy);
}
// apply the velocity to the ball
ball.setVelocity(dx, dy);
}
public static void moveBalls(Ball[] balls, DrawSurface d, int height,
int width, int minHeight, int minWidth) {
for (Ball ball : balls) {
updateBalVelocity(ball, width, height, minWidth, minHeight);
ball.moveOneStep();
d.setColor(ball.getColor());
d.fillCircle(ball.getX(), ball.getY(), ball.getSize());
ball.drawOn(d);
}
}
并在run方法中:
while (true) {
...
// move balls
BouncingBallHelper.moveBalls(ballsD1, d, 500, 500, 50, 50);
BouncingBallHelper.moveBalls(ballsD2, d, 600, 600, 450, 450);
gui.show(d);
// wait for 50 milliseconds.
sleeper.sleepFor(50);
}