/** Reset ball to an initial state */ private void serveBall() { mBall.x = getWidth() / 2; mBall.y = getHeight() / 2; mBall.speed = Ball.SPEED + mBallSpeedModifier; mBall.randomAngle(); mBall.pause(); }
public BallsFrame() throws HeadlessException { super("Funny balls"); setLayout(new BorderLayout()); executorService = Executors.newScheduledThreadPool(1); ballsPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (blueBallVisible) { g.setColor(Color.BLUE); g.fillOval(blueBall.x, getHeight() / 2, BALL_DIAGONAL, BALL_DIAGONAL); } g.setColor(Color.RED); g.fillOval(redBall.x, getHeight() / 2, BALL_DIAGONAL, BALL_DIAGONAL); } }; add(ballsPanel, BorderLayout.CENTER); blueBallSwitch = new JCheckBox("Collision", true); blueBallSwitch.addItemListener( e -> { if (blueBallVisible = blueBallSwitch.isSelected()) { int x; do x = random.nextInt(getWidth() - BALL_DIAGONAL); while (redBall.x <= x && x <= redBall.rightX() || redBall.x <= x + BALL_DIAGONAL && x + BALL_DIAGONAL <= redBall.rightX()); blueBall.x = x; } }); add(blueBallSwitch, BorderLayout.SOUTH); blueBallVisible = true; moveToRight = true; setSize(500, 500); }
@Override public void draw(Canvas c) { inner_.dx = this.dx; inner_.dy = this.dy; inner_.x = this.x; inner_.y = this.y; super.draw(c); inner_.draw(c); }
private void startAnimation() { redBall = new Ball(1); blueBall = new Ball(getWidth() / 2); executorService.scheduleAtFixedRate( () -> { if (redBall.rightX() >= getWidth() || redBall.x <= 0 || blueBallVisible && redBall.intersectsWith(blueBall)) moveToRight = !moveToRight; redBall.x += moveToRight ? 1 : -1; ballsPanel.repaint(); }, 1, 5, TimeUnit.MILLISECONDS); }
protected void handleBottomFastBounce(Paddle paddle, float px, float py) { if (mBall.goingDown() == false) return; float bx = mBall.x; float by = mBall.y + Ball.RADIUS; float pbx = px; float pby = py + Ball.RADIUS; float dyp = by - paddle.getTop(); float xc = bx + (bx - pbx) * dyp / (pby - by); if (by > paddle.getTop() && pby < paddle.getTop() && xc > paddle.getLeft() && xc < paddle.getRight()) { mBall.x = xc; mBall.y = paddle.getTop() - Ball.RADIUS; mBall.bouncePaddle(paddle); playSound(mPaddleSFX); increaseDifficulty(); } }
protected void handleTopFastBounce(Paddle paddle, float px, float py) { if (mBall.goingUp() == false) return; float tx = mBall.x; float ty = mBall.y - Ball.RADIUS; float ptx = px; float pty = py - Ball.RADIUS; float dyp = ty - paddle.getBottom(); float xc = tx + (tx - ptx) * dyp / (ty - pty); if (ty < paddle.getBottom() && pty > paddle.getBottom() && xc > paddle.getLeft() && xc < paddle.getRight()) { mBall.x = xc; mBall.y = paddle.getBottom() + Ball.RADIUS; mBall.bouncePaddle(paddle); playSound(mPaddleSFX); increaseDifficulty(); } }