Skip to content

Instantly share code, notes, and snippets.

@alexanderbazo
Created December 4, 2020 10:51
Show Gist options
  • Save alexanderbazo/76e1d31041c747890347a89dd168bce0 to your computer and use it in GitHub Desktop.
Save alexanderbazo/76e1d31041c747890347a89dd168bce0 to your computer and use it in GitHub Desktop.
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 Circle circle;
private boolean isMovingRight = true;
private int currentSpeed = 10;
@Override
public void initialize() {
setCanvasSize(CANVAS_WIDTH, CANVAS_HEIGHT);
circle = new Circle(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2, 25, Colors.RED);
}
@Override
public void draw() {
drawBackground(BACKGROUND_COLOR);
updateCircle();
circle.draw();
}
// Diese Methode bewegt den Kreis mit der aktuellen Geschwindigkeit in die aktuelle Bewegungsrichtung und ändert diese ggf.
private void updateCircle() {
if (isMovingRight) {
circle.move(currentSpeed, 0);
} else {
circle.move(-currentSpeed, 0);
}
if (circle.getXPos() - circle.getRadius() > CANVAS_WIDTH) {
isMovingRight = false;
}
if (circle.getXPos() < -circle.getWidth()) {
isMovingRight = true;
}
}
// Bei Tastendruck wird die Bewegungsgeschwindigkeit angepasst
@Override
public void onKeyPressed(KeyPressedEvent event) {
super.onKeyPressed(event);
if (event.getKeyCode() == KeyPressedEvent.VK_UP) {
currentSpeed++;
}
if (event.getKeyCode() == KeyPressedEvent.VK_DOWN) {
currentSpeed--;
}
if (currentSpeed <= 0) {
currentSpeed = 1;
}
}
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