Coin.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // FIXME
  2. keepAlive = typeof(keepAlive) == "undefined" ? [] : keepAlive;
  3. keepAlive.push(self);
  4. var glmatrix = require("gl-matrix");
  5. var vec2 = glmatrix.vec2;
  6. var node = self.node;
  7. // Resources
  8. var animationSet = cache.getResource("AnimationSet2D", "Sprites/GoldIcon.scml");
  9. var coinSound = cache.getResource("Sound","Sounds/Pickup_Coin8.ogg");
  10. var coinBounceSound = cache.getResource("Sound","Sounds/Coin_Bounce.ogg");
  11. var sprite = node.createComponent("AnimatedSprite2D");
  12. sprite.setAnimation(animationSet, "idle");
  13. sprite.setLayer(100);
  14. var activated = false;
  15. var body;
  16. function onPlayerHit() {
  17. // sprite enabled is not removing the sprite
  18. node.scale2D = [0, 0];
  19. sprite.enabled = false;
  20. body.enabled = false;
  21. self.soundSource.gain = 1.0;
  22. self.soundSource.play(coinSound );
  23. }
  24. self.onPhysicsBeginContact2D = function(world, bodyA, bodyB, nodeA, nodeB) {
  25. if (nodeA == ThePlayer.node && nodeB == node) {
  26. onPlayerHit();
  27. }
  28. else if (nodeB == node)
  29. {
  30. var vel = body.linearVelocity;
  31. if (vec2.length(vel) > 3)
  32. {
  33. self.soundSource.gain = .4;
  34. self.soundSource.play(coinBounceSound);
  35. }
  36. }
  37. }
  38. function start() {
  39. self.soundSource = node.createComponent("SoundSource");
  40. self.soundSource.soundType = Atomic.SOUND_EFFECT;
  41. // would just like to listen to body collisions here
  42. self.listenToEvent(null, "PhysicsBeginContact2D", self.onPhysicsBeginContact2D);
  43. }
  44. function update(timeStep) {
  45. if (activated)
  46. return false;
  47. if (vec2.distance(cameraNode.position2D, node.position2D) < 3.0) {
  48. activated = true;
  49. body = node.createComponent("RigidBody2D");
  50. body.setBodyType(Atomic.BT_DYNAMIC);
  51. body.fixedRotation = true;
  52. var circle = node.createComponent("CollisionCircle2D");
  53. // Set radius
  54. circle.setRadius(.3);
  55. // Set density
  56. circle.setDensity(1.0);
  57. // Set friction.
  58. circle.friction = .2;
  59. // Set restitution
  60. circle.setRestitution(.8);
  61. }
  62. }