Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Graphics;
- import java.util.Random;
- public class Ball
- {
- public int x, y, width = 40, height = 40;
- public int moveX, moveY;
- public Random random;
- public int amountOfHits;
- private Pong pong;
- public Ball(Pong pong)
- {
- this.pong = pong;
- this.random = new Random();
- spawn();
- }
- public void update(Paddle paddle1, Paddle paddle2)
- {
- int speed = 5;
- this.x += moveX * speed;
- this.y += moveY * speed;
- if(this.y + height - moveY > pong.height || this.y + moveY < 0)
- {
- if(this.moveY < 0)
- {
- this.moveY = random.nextInt(4);
- if(moveY == 0)
- {
- moveY = 1;
- }
- }
- else
- {
- this.moveY = -random.nextInt(4);
- this.y = pong.height - height;
- if(moveY == 0)
- {
- moveY = -1;
- }
- }
- }
- if (checkCollision(paddle1) == 1)
- {
- this.moveX = 1 + (amountOfHits / 5);
- this.moveY = -2 + random.nextInt(4);
- if (moveY == 0)
- {
- moveY = 1;
- }
- amountOfHits++;
- }
- else if (checkCollision(paddle2) == 1)
- {
- this.moveX = -1 - (amountOfHits / 5);
- this.moveY = -2 + random.nextInt(4);
- if (moveY == 0)
- {
- moveY = 1;
- }
- amountOfHits++;
- }
- }
- public void spawn()
- {
- this.amountOfHits = 0;
- this.x = pong.width/2 - this.width/2;
- this.y = pong.height/2 - this.height/2;
- this.moveY = -2 + random.nextInt(4);
- if(moveY == 0)
- {
- moveY = 1;
- }
- if(random.nextBoolean())
- {
- moveX = 1;
- }
- else
- {
- moveX = -1;
- }
- }
- public int checkCollision(Paddle paddle)
- {
- if (this.x < paddle.x + paddle.width && this.x + width > paddle.x && this.y < paddle.y + paddle.height && this.y + height > paddle.y)
- {
- return 1; //bounce
- }
- else if ((paddle.x > x && paddle.paddleNumber == 1) || (paddle.x < x - width && paddle.paddleNumber == 2))
- {
- return 2; //score
- }
- return 0; //nothing
- }
- public void render(Graphics g)
- {
- g.setColor(Color.BLACK);
- g.fillOval(x, y, width, height);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement