ilham_syamsuddin

Untitled

Dec 1st, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. //package Pong;
  2. import java.awt.Color;
  3. import java.awt.Graphics;
  4. import java.util.Random;
  5.  
  6. public class Ball
  7. {
  8. public int x , y, width = 25, height = 25;
  9. public int motionX, motionY;
  10. public Random random;
  11. private Pong pong;
  12. public int amountOfHits;
  13. public Ball(Pong pong)
  14. {
  15. this.pong = pong;
  16. this.random = new Random();
  17. spawn();
  18. }
  19.  
  20. public void update( Paddle paddle1, Paddle paddle2)
  21. {
  22. int speed = 5;
  23. this.x += motionX * speed;
  24. this.y += motionY * speed;
  25. if(this.y + height - motionY > pong.height || this.y + motionY < 0)
  26. {
  27. if(this.motionY < 0)
  28. {
  29. this.y = 0;
  30. this.motionY = random.nextInt(4);
  31.  
  32. if(motionY == 0)
  33. {
  34. motionY = 1;
  35. }
  36. }
  37. else
  38. {
  39. this.motionY = -random.nextInt(4);
  40. this.y = pong.height - height;
  41.  
  42. if(motionY == 0)
  43. {
  44. motionY = -1;
  45. }
  46. }
  47. }
  48.  
  49. if(checkCollision(paddle1) == 1)
  50. {
  51. this.motionX = 1 + (amountOfHits/5);
  52. this.motionY =-2 + random.nextInt(4);
  53.  
  54. if(motionY == 0)
  55. {
  56. motionY = 1;
  57. }
  58. amountOfHits++;
  59. }
  60. else if(checkCollision(paddle2) == 1)
  61. {
  62. this.motionX = -1 -(amountOfHits/5);
  63. this.motionY =-2 + random.nextInt(4);
  64.  
  65. if(motionY == 0)
  66. {
  67. motionY = 1;
  68. }
  69. amountOfHits++;
  70. }
  71.  
  72. if(checkCollision(paddle1) == 2)
  73. {
  74. paddle2.score++;
  75. spawn();
  76. }
  77.  
  78. if(checkCollision(paddle2) == 2)
  79. {
  80. paddle1.score++;
  81. spawn();
  82. }
  83. }
  84.  
  85. public void spawn()
  86. {
  87. this.amountOfHits = 0;
  88. this.x = pong.width / 2 - this.width / 2;
  89. this.y = pong.height / 2 - this.height / 2;
  90.  
  91. this.motionY = -2 + random.nextInt(4);
  92.  
  93. if (motionY == 0)
  94. {
  95. motionY = 1;
  96. }
  97.  
  98. else
  99. {
  100. motionX = -1;
  101. }
  102. }
  103.  
  104. public int checkCollision(Paddle paddle)
  105. {
  106. if (this.x < paddle.x + paddle.width && this.x + width > paddle.x && this.y < paddle.y + paddle.height && this.y + height > paddle.y)
  107. {
  108. return 1; //bounce
  109. }
  110. else if ((paddle.x > x && paddle.paddleNumber == 1) || (paddle.x < x - width && paddle.paddleNumber == 2))
  111. {
  112. return 2; //score
  113. }
  114. return 0; //nothing
  115. }
  116.  
  117. public void render(Graphics g)
  118. {
  119. g.setColor(Color.WHITE);
  120. g.fillOval(x, y, width, height);
  121. }
  122. }
Advertisement
Add Comment
Please, Sign In to add comment