Coin.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. "atomic component";
  2. //requiring gl-matrix module
  3. var glmatrix = require("gl-matrix");
  4. var vec2 = glmatrix.vec2;
  5. //settings some fields to make them visible from editor
  6. //the first parameter is a type, the second is a default value
  7. var inspectorFields = {
  8. pickupSound: ["Sound", "Sounds/Pickup_Coin8.ogg"],
  9. bounceSound: ["Sound"]
  10. }
  11. //A Coin
  12. var component = function(self) {
  13. var node = self.node;
  14. //getting main camera from our current scene
  15. var camera = self.node.scene.getMainCamera();
  16. var cameraNode = camera.node;
  17. // Resources
  18. //getting AnimatedSprite2D component
  19. var sprite = node.getComponent("AnimatedSprite2D")
  20. sprite.setAnimation("idle");
  21. //getting SoundSource component
  22. var soundSource = node.getComponent("SoundSource");
  23. var activated = false;
  24. var body;
  25. self.update = function(timeStep) {
  26. if (activated)
  27. return false;
  28. if (vec2.distance(cameraNode.position2D, node.position2D) < 3.0) {
  29. activated = true;
  30. //setting rigid body
  31. body = node.createComponent("RigidBody2D");
  32. //our body is Dynamic
  33. body.setBodyType(Atomic.BT_DYNAMIC);
  34. //fix rotation
  35. body.fixedRotation = true;
  36. //don't make our body to cast shadows
  37. body.castShadows = false;
  38. //subscribing to PhysicsBeginContact2D event, and specifying a callback
  39. self.subscribeToEvent("PhysicsBeginContact2D", function(ev) {
  40. //checking if nodeB is our current node
  41. if (ev.nodeB == node) {
  42. //checking if nodeA(another node) is a Player
  43. if (ev.nodeA && ev.nodeA.name == "Player") {
  44. //picking up a coin
  45. //setting scale to 0, 0
  46. node.scale2D = [0, 0];
  47. //disable sprite
  48. sprite.enabled = false;
  49. //disable body
  50. body.enabled = false;
  51. if (self.pickupSound) {
  52. soundSource.gain = 1.0;
  53. //playing pickupSound
  54. soundSource.play(self.pickupSound);
  55. }
  56. //if it's not a player, and we have bounceSound, then play it
  57. } else if (self.bounceSound) {
  58. var vel = body.linearVelocity;
  59. if (vec2.length(vel) > 3) {
  60. soundSource.gain = .3;
  61. soundSource.play(self.bounceSound);
  62. }
  63. }
  64. }
  65. });
  66. //adding circle colision shape
  67. var circle = node.createComponent("CollisionCircle2D");
  68. // Set radius
  69. circle.setRadius(.3);
  70. // Set density
  71. circle.setDensity(1.0);
  72. // Set friction.
  73. circle.friction = .2;
  74. // Set restitution
  75. circle.setRestitution(.8);
  76. }
  77. }
  78. }
  79. exports.component = component;