Advertisement
Guest User

Ball.java

a guest
May 18th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. package game.pong;
  2.  
  3. import java.awt.*;
  4.  
  5. public class Ball {
  6.    
  7.     private int ballSize = 15;
  8.    
  9.     private int x = Game.WIDTH / 2;
  10.     private int y = Game.HEIGHT / 2;
  11.    
  12.     private int xVelocity = -2;
  13.     private int yVelocity = -2;
  14.    
  15.     public void update() {
  16.        
  17.         x = x + xVelocity;
  18.         y = y + yVelocity;
  19.        
  20.         if(x < 0){
  21.             xVelocity = 3;
  22.         }else if(x + ballSize + 5 > 600){
  23.             xVelocity = -3;
  24.         }
  25.        
  26.         if(y < 0){
  27.             yVelocity = 3;
  28.         }else if(y + ballSize * 2 + 10 > 400){
  29.             yVelocity = -3;
  30.         }
  31. }
  32.    
  33.     public void paint(Graphics g){
  34.         g.setColor(Color.WHITE);
  35.         g.fillOval(x, y, ballSize, ballSize);
  36.     }
  37.    
  38.     private void reverseVelocity(){
  39.         xVelocity = -xVelocity + 2;
  40.     }
  41.    
  42.     public void hasCollided(Player player){
  43.         if(this.x > player.getX() && this.x < player.getX() + player.getWidth()){
  44.             if(this.y > player.getY() && this.y < player.getY() + player.getHeight()){
  45.                 reverseVelocity();
  46.             }
  47.         }
  48.     }
  49.    
  50.     public void hasCollided(Computer computer){
  51.         if(this.x > computer.getX() && this.x < computer.getX() + computer.getWidth()){
  52.             if(this.y > computer.getY() && this.y < computer.getY() + computer.getHeight()){
  53.                 reverseVelocity();
  54.             }
  55.         }
  56.     }
  57.  
  58.     public int getY() {
  59.         return y;
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement