Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package testGame;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Rectangle;
- import java.util.Random;
- class Ball extends Rectangle{
- double xVel, yVel;
- Ball() {
- x = Game.SCREEN_WIDTH / 2;
- y = Game.SCREEN_HEIGHT / 2;
- width = height = 30;
- Random rndm = new Random();
- while (xVel != 0 || yVel != 0) {
- if (rndm.nextBoolean()) {
- xVel = rndm.nextInt(4) + 1;
- yVel = rndm.nextInt(4) + 1;
- } else {
- xVel = -rndm.nextInt(4) + 1;
- yVel = -rndm.nextInt(4) + 1;
- }
- }
- //DEBUG: set a starting speed
- xVel = yVel = -1.5;
- }
- void draw(Graphics g) {
- g.setColor(Color.white);
- g.fillOval(x, y, width, height);
- }
- void move() {
- //move the ball before checking for collisions
- x += xVel;
- y += yVel;
- bounceOffWalls(); //top and bottom
- // <-- add some sort of method to see if the ball hits the left or right walls
- }
- void bounceOffWalls() {
- //bounce off top wall
- if (y < 0 && yVel < 0) {
- y=0;
- yVel = -yVel;
- }
- //bounce off bottom wall
- if (y+height > Game.SCREEN_HEIGHT && yVel > 0) {
- y = Game.SCREEN_HEIGHT - height;
- yVel = -yVel;
- }
- }
- void checkPlayerCollision(Paddle player) {
- //Since they are both rectangles, we can check for collisions this way
- //but we only want the collision to happen if it's coming from the right side
- if (player.intersects(this) && this.xVel < 0) {
- //undo the last move of the ball to get it out of the paddle
- x -= xVel;
- y -= yVel;
- //now change the x velocity to the opposite sign.
- //Since the paddle is long and thin, this should suffice.
- this.xVel = -xVel;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement