Created
December 4, 2020 10:50
-
-
Save alexanderbazo/9e4069f249d909a428d3fdabafcacb62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BouncingBalls extends GraphicsApp { | |
private static final int CANVAS_WIDTH = 1280; | |
private static final int CANVAS_HEIGHT = 360; | |
private static final Color BACKGROUND_COLOR = Colors.WHITE; | |
private static final int DEFAULT_SPEED = 5; | |
private static final int MIN_SPEED = 1; | |
private static final int BALL_RADIUS = 25; | |
private static final Color BALL_COLOR = Colors.RED; | |
private Circle ball; | |
private boolean currentlyMovingToRight = true; | |
private int currentSpeed = DEFAULT_SPEED; | |
@Override | |
public void initialize() { | |
setCanvasSize(CANVAS_WIDTH, CANVAS_HEIGHT); | |
// Erstellen des Balls am Mittelpunkt der Zeichenfläche | |
ball = new Circle(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2, BALL_RADIUS, BALL_COLOR); | |
} | |
@Override | |
public void draw() { | |
drawBackground(BACKGROUND_COLOR); | |
updateBall(); | |
drawBall(); | |
} | |
private void updateBall() { | |
// Umkehr der Bewegungsrichtung, falls der Ball den Bildschirmrand im letzten Frame verlassen hat | |
if (hasLeftScreen(ball)) { | |
currentlyMovingToRight = !currentlyMovingToRight; | |
} | |
int speed = currentlyMovingToRight ? currentSpeed : -currentSpeed; | |
ball.move(speed, 0); | |
} | |
// Prüft ob das übergebene Circle-Objekt den rechten oder linken Bildschirmrand verlassen hat | |
private boolean hasLeftScreen(Circle ball) { | |
if ((ball.getXPos() - ball.getRadius()) >= CANVAS_WIDTH) { | |
return true; | |
} | |
if ((ball.getXPos() + ball.getRadius()) <= 0) { | |
return true; | |
} | |
return false; | |
} | |
private void drawBall() { | |
ball.draw(); | |
} | |
@Override | |
public void onKeyPressed(KeyPressedEvent event) { | |
super.onKeyPressed(event); | |
switch (event.getKeyCode()) { | |
case KeyPressedEvent.VK_UP: | |
increaseSpeed(); | |
break; | |
case KeyPressedEvent.VK_DOWN: | |
decreaseSpeed(); | |
break; | |
default: | |
break; | |
} | |
} | |
private void increaseSpeed() { | |
currentSpeed++; | |
} | |
private void decreaseSpeed() { | |
currentSpeed--; | |
if (currentSpeed < MIN_SPEED) { | |
currentSpeed = MIN_SPEED; | |
} | |
} | |
public static void main(String[] args) { | |
GraphicsAppLauncher.launch(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment