Ball.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "atomic component";
  2. var MAX_SPEED = 4;
  3. //A Ball component
  4. exports.component = function(self) {
  5. //get a sound source from the scene
  6. var brickDestroySound = self.scene.getChild("BrickSound").getComponent("SoundSource");
  7. //function to play the brick destroy sound
  8. function playBrickDestroySound() {
  9. brickDestroySound.play(brickDestroySound.sound);
  10. }
  11. self.start = function() {
  12. //define node name
  13. self.node.name = "Ball";
  14. self.rigidBody = self.getComponent("RigidBody2D");
  15. self.subscribeToEvent("PhysicsBeginContact2D", function(data){
  16. //get an collidable object
  17. var other = (data.nodeA == self.node) ? data.nodeB : data.nodeA;
  18. //check collision for a brick
  19. if (other.name.indexOf("Brick") > -1) {
  20. //play brick destroy sound
  21. playBrickDestroySound();
  22. //remove brick
  23. Atomic.destroy(other);
  24. }
  25. });
  26. self.zoom = self.node.scene.getMainCamera().zoom;
  27. };
  28. self.update = function(delta) {
  29. if (!self.started) return;
  30. //if x || y velocity of the ball is around zero,
  31. //add 1 velocity to prevent bound up / down or left / right for ever
  32. if (Math.abs(self.rigidBody.linearVelocity[0]) <= 0.0001)
  33. self.rigidBody.linearVelocity = [MAX_SPEED, self.rigidBody.linearVelocity[1]];
  34. if (Math.abs(self.rigidBody.linearVelocity[1]) <= 0.0001)
  35. self.rigidBody.linearVelocity = [self.rigidBody.linearVelocity[0], MAX_SPEED];
  36. //normalize a ball speed
  37. if (self.rigidBody.linearVelocity[0] > MAX_SPEED)
  38. self.rigidBody.linearVelocity = [MAX_SPEED, self.rigidBody.linearVelocity[1]];
  39. if (self.rigidBody.linearVelocity[1] > MAX_SPEED)
  40. self.rigidBody.linearVelocity = [self.rigidBody.linearVelocity[0], MAX_SPEED];
  41. //check if a ball fell down
  42. if (self.node.position2D[1] <= -Atomic.graphics.height/2*Atomic.PIXEL_SIZE/self.zoom) {
  43. self.remove();
  44. self.sendEvent("CreateNewBall");
  45. }
  46. };
  47. };