ball.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. function Ball(options) {
  2. if (typeof(options) == 'undefined') options={};
  3. var x = options.x !== undefined ? options.x : 0;
  4. var y = options.y !== undefined ? options.y : 0;
  5. var dx = options.dx !== undefined ? options.dx : 0;
  6. var dy = options.dy !== undefined ? options.dy : 0;
  7. var sx = options.sx !== undefined ? options.sx : 0;
  8. var sy = options.sy !== undefined ? options.sy : 0;
  9. var size = options.size !== undefined ? options.size : 0;
  10. function update(ctx, paddle) {
  11. // Get the start x and y for the ball.
  12. var aX = x;
  13. var aY = y;
  14. // Move the ball left or right.
  15. x += dx * sx;
  16. // Check to see if the ball hit the left wall.
  17. // If it did, bounce to the right.
  18. if (x <= (size / 2)) {
  19. x = size / 2;
  20. dx = 1;
  21. }
  22. // Check to see if the ball hit the right wall.
  23. // If it did, bounce to the left.
  24. if (x >= (ctx.canvas.width - (size / 2))) {
  25. x = (ctx.canvas.width - (size / 2));
  26. dx = -1;
  27. }
  28. // Move the ball up or down.
  29. y += dy * sy;
  30. // Check to see if the ball hit the ceiling.
  31. // Bounce down if it did.
  32. if (y <= (size / 2)) {
  33. y = size / 2;
  34. dy = 1;
  35. }
  36. // Check to see if the ball hit the paddle.
  37. // Ball line aX, aY to x, y
  38. // Paddle line paddle.x - (paddle.size / 2), paddle.y to paddle.x + (paddle.size / 2), paddle.y
  39. // y = mx + b
  40. if (x >= paddle.getX1() &&
  41. x <= paddle.getX2() &&
  42. aY <= paddle.getY() && y >= paddle.getY()) {
  43. y = paddle.getY() - size;
  44. dy = -1;
  45. sx++;
  46. sy++;
  47. paddle.increaseDifficulty();
  48. game.add1ToScore();
  49. }
  50. // Check to see if the ball goes off the bottom
  51. // of the screen. If it did, game over!
  52. if (y >= (ctx.canvas.height - (size / 2))) {
  53. game.endGame();
  54. }
  55. }
  56. function draw(ctx) {
  57. ctx.beginPath();
  58. ctx.fillStyle = '#000000';
  59. ctx.ellipse(x, y, size, size, 0, 0, 360);
  60. ctx.fill();
  61. }
  62. return {
  63. 'x': x,
  64. 'y': y,
  65. 'dx': dx,
  66. 'dy': dy,
  67. 'sx': sx,
  68. 'sy': sy,
  69. 'size': size,
  70. 'update': update,
  71. 'draw': draw
  72. };
  73. }