# Ball_v2.java

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