Ball.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. other.remove();
  24. }
  25. });
  26. }
  27. self.update = function(delta) {
  28. if (!self.started) return;
  29. //if x || y velocity of the ball is around zero,
  30. //add 1 velocity to prevent bound up / down or left / right for ever
  31. if (Math.abs(self.rigidBody.linearVelocity[0]) <= 0.5)
  32. self.rigidBody.linearVelocity = [self.rigidBody.linearVelocity[0]+1, self.rigidBody.linearVelocity[1]];
  33. if (Math.abs(self.rigidBody.linearVelocity[1]) <= 0.5)
  34. self.rigidBody.linearVelocity = [self.rigidBody.linearVelocity[0], self.rigidBody.linearVelocity[1]+1];
  35. //normalize a ball speed
  36. if (self.rigidBody.linearVelocity[0] > MAX_SPEED)
  37. self.rigidBody.linearVelocity = [MAX_SPEED, self.rigidBody.linearVelocity[1]];
  38. if (self.rigidBody.linearVelocity[1] > MAX_SPEED)
  39. self.rigidBody.linearVelocity = [self.rigidBody.linearVelocity[0], MAX_SPEED];
  40. //check if a ball fell down
  41. if (self.node.position2D[1] <= -4) {
  42. self.remove();
  43. self.sendEvent("CreateNewBall");
  44. }
  45. }
  46. }