Coin.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var glmatrix = require("gl-matrix");
  2. var vec2 = glmatrix.vec2;
  3. var game = Atomic.game;
  4. var cameraNode = game.cameraNode;
  5. var cache = game.cache;
  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. var light;
  17. function onPlayerHit() {
  18. // sprite enabled is not removing the sprite
  19. light.enabled = false;
  20. node.scale2D = [0, 0];
  21. sprite.enabled = false;
  22. body.enabled = false;
  23. self.soundSource.gain = 1.0;
  24. self.soundSource.play(coinSound);
  25. }
  26. self.onPhysicsBeginContact2D = function(world, bodyA, bodyB, nodeA, nodeB) {
  27. if (nodeA == Platformer.level.player.node && nodeB == node) {
  28. onPlayerHit();
  29. } else if (nodeB == node) {
  30. var vel = body.linearVelocity;
  31. if (vec2.length(vel) > 3) {
  32. self.soundSource.gain = .3;
  33. self.soundSource.play(coinBounceSound);
  34. }
  35. }
  36. }
  37. function start() {
  38. self.soundSource = node.createComponent("SoundSource");
  39. self.soundSource.soundType = Atomic.SOUND_EFFECT;
  40. light = node.createComponent("PointLight2D");
  41. if (Platformer.daytime)
  42. light.color = [1, 1, .56, .4];
  43. else
  44. light.color = [1, 1, .56, .8];
  45. light.radius = .85;
  46. Platformer.lightGroup.addLight(light);
  47. // would just like to listen to body collisions here
  48. self.listenToEvent(null, "PhysicsBeginContact2D", self.onPhysicsBeginContact2D);
  49. }
  50. function update(timeStep) {
  51. if (activated)
  52. return false;
  53. if (vec2.distance(cameraNode.position2D, node.position2D) < 3.0) {
  54. activated = true;
  55. body = node.createComponent("RigidBody2D");
  56. body.setBodyType(Atomic.BT_DYNAMIC);
  57. body.fixedRotation = true;
  58. body.castShadows = false;
  59. var circle = node.createComponent("CollisionCircle2D");
  60. // Set radius
  61. circle.setRadius(.3);
  62. // Set density
  63. circle.setDensity(1.0);
  64. // Set friction.
  65. circle.friction = .2;
  66. // Set restitution
  67. circle.setRestitution(.8);
  68. }
  69. }