Advertisement
xeromino

nod

Jun 4th, 2017
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. /*
  2.  * MovingBall class
  3.  *
  4.  * Represents a moving ball that moves in a single direction
  5.  *
  6.  */
  7. class MovingBall {
  8.  
  9.   float x, y;        // position
  10.   float tx, ty;      // target in x and y
  11.   float step, inc;
  12.   float radius;
  13.  
  14.   int direction;
  15.   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!
  16.  
  17.   // constructor
  18.   // create a moving ball at the supplied position (x_, y_)
  19.   MovingBall(float x_, float y_, int numOfDirections_) {
  20.     x = x_;
  21.     y = y_;
  22.     nod = numOfDirections_;
  23.  
  24.     reset();
  25.   }
  26.  
  27.   // run
  28.   // calls move() followed by display()
  29.   void run() {
  30.     this.move();    // this refers to the current object
  31.     this.display();
  32.   }
  33.  
  34.   // move
  35.   // move the ball in the desired direction
  36.   void move() {
  37.  
  38.     step -= inc;
  39.  
  40.     if (step < 0) {
  41.       x = tx;
  42.       y = ty;
  43.       reset();
  44.     }
  45.  
  46.     x = lerp(tx, x, step);
  47.     y = lerp(ty, y, step);
  48.  
  49.     checkBounds();
  50.   }
  51.  
  52.   // checkBounds
  53.   // checks that the ball is within the display window.
  54.   // If it reaches the edge, move in the opposite direction
  55.   void checkBounds() {
  56.     if (x <= 0 || x >= width || y <= 0 || y >= height) {
  57.       x = width/2;
  58.       y = height/2;
  59.       reset();
  60.     }
  61.   }
  62.  
  63.   void reset() {
  64.     step = 1;
  65.     inc = random(0.01);
  66.     radius = random(10, 50);
  67.     int numOfDirections = nod;
  68.     float angleUnit = TWO_PI/numOfDirections;
  69.     direction = (int) random(numOfDirections);
  70.  
  71.     tx = x + radius*cos(direction * angleUnit);
  72.     ty = y + radius*sin(direction * angleUnit);
  73.   }
  74.  
  75.   // display method
  76.   //
  77.   //
  78.   void display() {
  79.     noStroke();
  80.     rectMode(CENTER);
  81.     fill(0, 30);
  82.     rect(tx, ty, 10, 10);
  83.     fill(255, 60);
  84.     ellipse(x, y, 2, 2);
  85.   }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement