Bat.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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.update = function(timestep) {
  14. time += timestep * 4;
  15. var waypoints = node.waypoints;
  16. //get node position, returns an array with two elements, the first is x, the second is y
  17. var pos = node.position2D;
  18. if (cwaypoint == -1 || vec2.distance(pos, waypoints[cwaypoint]) < .5) {
  19. cwaypoint = Math.round(Math.random() * (waypoints.length - 1));
  20. return;
  21. }
  22. var dir = vec2.create();
  23. var goal = waypoints[cwaypoint];
  24. vec2.subtract(dir, goal, pos);
  25. vec2.normalize(dir, dir);
  26. vec2.scale(dir, dir, timestep * 2);
  27. if (dir[0] < 0)
  28. sprite.flipX = true;
  29. else
  30. sprite.flipX = false;
  31. vec2.add(pos, pos, dir);
  32. //set position of our node
  33. node.position2D = pos;
  34. }
  35. }
  36. exports.component = component;