Advertisement
fosterbl

Ball class Processing - put in new TAB

Feb 7th, 2020
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. class Ball {
  2.   //instance variables
  3.   private int diameter;
  4.   private color colour;
  5.   private int x, y;
  6.   private int xVel, yVel;
  7.  
  8.   //constructor - make a random ball
  9.   public Ball() {
  10.     x = width / 2;
  11.     y = height / 2;
  12.     diameter = (int)(Math.random() * 76 + 25);//25 - 100
  13.     xVel = (int)(Math.random() * 11 - 5);//-5 - 5
  14.     yVel = (int)(Math.random() * 11 - 5);//-5 - 5
  15.     colour = color( (int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256));
  16.   }
  17.  
  18.   //methods/abilities
  19.  
  20.   //draw the ball on the screen
  21.   public void display() {
  22.     fill( colour );
  23.     ellipse(x, y, diameter, diameter);
  24.   }
  25.  
  26.   //make the ball "move": change the x and y by their respective velocities
  27.   public void move() {
  28.     x += xVel;
  29.     y += yVel;
  30.   }
  31.  
  32.   //make the ball "bounce": make the xVel/yVel flipflop depending on wall hit
  33.   public void bounce() {
  34.     if( xVel > 0 && (x + diameter/2 + xVel) >= width ) xVel = -xVel;
  35.     else if( xVel < 0 && (x - diameter/2 + xVel) <= 0 ) xVel = -xVel;
  36.     if( yVel > 0 && (y + diameter/2 + yVel) >= height ) yVel = -yVel;
  37.     else if( yVel < 0 && (y - diameter/2 + yVel) <= 0 ) yVel = -yVel;
  38.   }
  39.  
  40.   //accessors
  41.   public int getDiameter(){ return diameter; }
  42.   public color getColor(){ return colour; }
  43.   public int getX(){ return x; }
  44.   public int getY(){ return y; }
  45.   public int getXVel(){ return xVel; }
  46.   public int getYVel(){ return yVel; }
  47.  
  48.   //mutators
  49.   public void setDiameter(int d){ diameter = d; }
  50.   public void setColor(color c){ colour = c; }
  51.   public void setX(int theX){ x = theX; }
  52.   public void setY(int theY){ y = theY; }
  53.   public void setXVel(int xv){ xVel = xv; }
  54.   public void setYVel(int yv){ yVel = yv; }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement