Butterfly.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'atomic component';
  2. var halfWidth = Atomic.graphics.width * Atomic.PIXEL_SIZE * 0.5;
  3. var halfHeight = Atomic.graphics.height * Atomic.PIXEL_SIZE * 0.5;
  4. var animationSet = Atomic.cache.getResource("AnimationSet2D", "Sprites/butterfly.scml");
  5. exports.component = function(self) {
  6. var node = self.node;
  7. self.speed = 1 + 2 * Math.random();
  8. self.rotationSpeed = 10;
  9. self.direction = Math.random() * Math.PI * 2;
  10. self.time = 0.0;
  11. //start function calls once, when component attached to the node
  12. self.start = function() {
  13. //pos is a array with 2 elements, the first is X, the second is Y
  14. self.pos = node.getPosition2D();
  15. //create AnimatedSprite2D component
  16. self.spr = node.createComponent("AnimatedSprite2D");
  17. self.spr.animationSet = animationSet;
  18. self.spr.setAnimation("idle");
  19. self.spr.color = [.1 + Math.random() * .9, .1 + Math.random() * .9, .1 + Math.random() * .9, 1];
  20. self.spr.blendMode = Atomic.BlendMode.BLEND_ALPHA;
  21. };
  22. self.update = function(timeStep) {
  23. self.time += timeStep;
  24. if (self.time % 1000 / 1000 < 0.5) self.desiredDirection = Math.random() * Math.PI * 2;
  25. self.direction = self.circWrapTo(self.direction, self.desiredDirection, self.rotationSpeed * timeStep);
  26. self.pos[0] += Math.cos(self.direction) * self.speed * timeStep;
  27. self.pos[1] += Math.sin(self.direction) * self.speed * timeStep;
  28. node.position2D = self.pos;
  29. node.rotation2D = (self.direction + Math.PI * 3 / 2) * (180 / Math.PI);
  30. //check if our butterfly is out of bounds
  31. if (self.pos[0] < -halfWidth || self.pos[1] < -halfHeight || self.pos[0] > halfWidth || self.pos[1] > halfHeight)
  32. node.remove();
  33. };
  34. //just a maths functions, nothing really interesting
  35. self.circWrapTo = function(value, target, step) {
  36. if (value == target) return target;
  37. var max = Math.PI * 2;
  38. var result = value;
  39. var d = self.wrappedDistance(value, target, max);
  40. if (Math.abs(d) < step) return target;
  41. result += (d < 0 ? -1 : 1) * step;
  42. if (result > max) result = result - max;
  43. else if (result < 0) result = max + result;
  44. return result;
  45. };
  46. self.wrappedDistance = function(a, b, max) {
  47. if (a == b) return 0;
  48. var l;
  49. var r;
  50. if (a < b) {
  51. l = -a - max + b;
  52. r = b - a;
  53. } else {
  54. l = b - a;
  55. r = max - a + b;
  56. }
  57. if (Math.abs(l) > Math.abs(r)) return r;
  58. else return l;
  59. };
  60. };