Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * MovingBall class
- *
- * Represents a moving ball that moves in a single direction
- *
- */
- class MovingBall {
- float x, y; // position
- float tx, ty; // target in x and y
- float step, inc;
- float radius;
- int direction;
- int nod; // this variable will make your numOfDirections_ variable accessible throughout your class, notice the added code in the constructor! then in reset() you set numOfDirections to nod et voilà, it works!
- // constructor
- // create a moving ball at the supplied position (x_, y_)
- MovingBall(float x_, float y_, int numOfDirections_) {
- x = x_;
- y = y_;
- nod = numOfDirections_;
- reset();
- }
- // run
- // calls move() followed by display()
- void run() {
- this.move(); // this refers to the current object
- this.display();
- }
- // move
- // move the ball in the desired direction
- void move() {
- step -= inc;
- if (step < 0) {
- x = tx;
- y = ty;
- reset();
- }
- x = lerp(tx, x, step);
- y = lerp(ty, y, step);
- checkBounds();
- }
- // checkBounds
- // checks that the ball is within the display window.
- // If it reaches the edge, move in the opposite direction
- void checkBounds() {
- if (x <= 0 || x >= width || y <= 0 || y >= height) {
- x = width/2;
- y = height/2;
- reset();
- }
- }
- void reset() {
- step = 1;
- inc = random(0.01);
- radius = random(10, 50);
- int numOfDirections = nod;
- float angleUnit = TWO_PI/numOfDirections;
- direction = (int) random(numOfDirections);
- tx = x + radius*cos(direction * angleUnit);
- ty = y + radius*sin(direction * angleUnit);
- }
- // display method
- //
- //
- void display() {
- noStroke();
- rectMode(CENTER);
- fill(0, 30);
- rect(tx, ty, 10, 10);
- fill(255, 60);
- ellipse(x, y, 2, 2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement