Created
December 4, 2020 10:51
-
-
Save alexanderbazo/76e1d31041c747890347a89dd168bce0 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 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