Skip to content

Instantly share code, notes, and snippets.

@niiicolai
Last active May 17, 2022 04:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niiicolai/b7bf280f984e6902c4a4573db6987864 to your computer and use it in GitHub Desktop.
Save niiicolai/b7bf280f984e6902c4a4573db6987864 to your computer and use it in GitHub Desktop.
class Ball {
// Current position
PVector position;
// Current direction
PVector direction;
// Diameter of the circle
float d = 15;
// The speed of the ball
float s = 5;
// Ball constructor
public Ball() {
resetMovement();
}
// Getter Methods
public PVector getPosition() {
return position;
}
// Reset position and randomize direction.
public void resetMovement() {
this.position = new PVector(width/2, height/2);
// Get a random speed
float speed = random(-s, s);
// Set the y direction to half of the speed
// to ensure it moves faster in the left or
// right direction
direction = new PVector(speed, speed/2);
}
// Set direction on the x-axis.
public void setDirection(float x) {
direction.x = x * speed;
}
// Updates the ball's position, add boundaries
// and draw its visuals.
public void update() {
// Add velocity
position.add(direction);
// Check if the ball has reached the top
// or the bottom of the screen.
if (position.y < 0 || position.y > height) {
// Invert the direction on the y-axis.
direction.y = -direction.y;
}
// Set the fill color to white.
fill(255);
// Draw the ball's circle.
circle(position.x, position.y, d);
}
public boolean overlapsWith(Player player) {
// Get player position,
// width, and height.
var p = player.getPosition();
var w = player.getWidth();
var h = player.getHeight();
// Calculate radius.
var r = d/2;
// Loop eight points.
for (int i = 0; i < 8; i++) {
// Convert i * 45 degrees to radians.
var degree = (i * 45) * (PI/180);
// Calculate x and y points by rotating a vector
// relative to the position 45 degrees
var x = r * cos(position.x + degree) + position.x;
var y = r * sin(position.y + degree) + position.y;
// Return true if the point is within on both
// the x-axis and the y-axis.
if (p.x < x && x < p.x + w &&
p.y < y && y < p.y + h) return true;
}
// If none of the points were within
// the player, return false.
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment