boxglue

Ball.java

May 7th, 2021
649
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package testGame;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Graphics;
  5. import java.awt.Rectangle;
  6. import java.util.Random;
  7.  
  8. class Ball extends Rectangle{
  9.  
  10.     double xVel, yVel;
  11.  
  12.     Ball() {
  13.         x = Game.SCREEN_WIDTH  / 2;
  14.         y = Game.SCREEN_HEIGHT / 2;
  15.         width = height = 30;
  16.         Random rndm = new Random();
  17.  
  18.         while (xVel != 0 || yVel != 0) {
  19.             if (rndm.nextBoolean()) {
  20.                 xVel = rndm.nextInt(4) + 1;
  21.                 yVel = rndm.nextInt(4) + 1;
  22.             } else {
  23.                 xVel = -rndm.nextInt(4) + 1;
  24.                 yVel = -rndm.nextInt(4) + 1;
  25.             }
  26.         }
  27.         //DEBUG: set a starting speed
  28.         xVel = yVel = -1.5;
  29.     }
  30.  
  31.     void draw(Graphics g) {
  32.         g.setColor(Color.white);
  33.         g.fillOval(x, y, width, height);
  34.     }
  35.  
  36.     void move() {
  37.        
  38.         //move the ball before checking for collisions
  39.         x += xVel;
  40.         y += yVel;
  41.        
  42.         bounceOffWalls(); //top and bottom
  43.         // <-- add some sort of method to see if the ball hits the left or right walls
  44.  
  45.     }
  46.    
  47.     void bounceOffWalls() {
  48.         //bounce off top wall
  49.         if (y < 0 && yVel < 0) {
  50.             y=0;
  51.             yVel = -yVel;
  52.         }
  53.         //bounce off bottom wall
  54.         if (y+height > Game.SCREEN_HEIGHT && yVel > 0) {
  55.             y = Game.SCREEN_HEIGHT - height;
  56.             yVel = -yVel;
  57.         }
  58.     }  
  59.  
  60.     void checkPlayerCollision(Paddle player) {
  61.         //Since they are both rectangles, we can check for collisions this way
  62.         //but we only want the collision to happen if it's coming from the right side
  63.         if (player.intersects(this) && this.xVel < 0) {
  64.             //undo the last move of the ball to get it out of the paddle
  65.             x -= xVel;
  66.             y -= yVel;
  67.             //now change the x velocity to the opposite sign.
  68.             //Since the paddle is long and thin, this should suffice.
  69.             this.xVel = -xVel;
  70.         }
  71.     }
  72.  
  73. }
  74.  
RAW Paste Data