Bat.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //requiring gl-matrix module
  2. //https://github.com/toji/gl-matrix for more information
  3. var glmatrix = require("gl-matrix");
  4. var vec2 = glmatrix.vec2;
  5. "atomic component";
  6. var component = function (self) {
  7. var node = self.node;
  8. //get a component from our current node
  9. var sprite = node.getComponent("AnimatedSprite2D");
  10. sprite.setAnimation("Fly");
  11. var cwaypoint = -1;
  12. var time = Math.random() * 10000;
  13. self.start = function() {
  14. var dayTime = require("GlobalVariables").dayTime;
  15. if(!dayTime) {
  16. //ok, it's a night, then create a light
  17. var light = node.createComponent("PointLight2D");
  18. light.color = [1, 0.1, 0.8, .85];
  19. light.radius = 1;
  20. }
  21. };
  22. self.update = function(timestep) {
  23. time += timestep * 4;
  24. var waypoints = node.waypoints;
  25. //get node position, returns an array with two elements, the first is x, the second is y
  26. var pos = node.position2D;
  27. if (cwaypoint == -1 || vec2.distance(pos, waypoints[cwaypoint]) < .5) {
  28. cwaypoint = Math.round(Math.random() * (waypoints.length - 1));
  29. return;
  30. }
  31. var dir = vec2.create();
  32. var goal = waypoints[cwaypoint];
  33. vec2.subtract(dir, goal, pos);
  34. vec2.normalize(dir, dir);
  35. vec2.scale(dir, dir, timestep * 2);
  36. if (dir[0] < 0)
  37. sprite.flipX = true;
  38. else
  39. sprite.flipX = false;
  40. vec2.add(pos, pos, dir);
  41. //set position of our node
  42. node.position2D = pos;
  43. };
  44. };
  45. exports.component = component;