MovingPlatform.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //requiring gl-matrix module
  2. var glmatrix = require("gl-matrix");
  3. var vec2 = glmatrix.vec2;
  4. "atomic component";
  5. // A moving platform
  6. var component = function (self) {
  7. var node = self.node;
  8. var MAX_VELOCITY = 2;
  9. var movingToStop = true;
  10. //Get RigidBody2D component
  11. var body = self.getComponent("RigidBody2D");
  12. //update function called each frame
  13. self.update = function(timeStep) {
  14. //get node position
  15. var pos = node.position2D;
  16. var dir = vec2.create();
  17. var dist = 0.0;
  18. if (movingToStop) {
  19. dist = vec2.distance(pos, node.stopPos);
  20. vec2.subtract(dir, node.stopPos, pos);
  21. vec2.normalize(dir, dir);
  22. if (dist < 0.5) {
  23. movingToStop = false;
  24. return;
  25. }
  26. } else {
  27. dist = vec2.distance(pos, node.startPos);
  28. vec2.subtract(dir, node.startPos, pos);
  29. vec2.normalize(dir, dir);
  30. if (dist < 0.5) {
  31. movingToStop = true;
  32. return;
  33. }
  34. }
  35. vec2.scale(dir, dir, dist);
  36. if (vec2.length(dir) > MAX_VELOCITY) {
  37. vec2.normalize(dir, dir);
  38. vec2.scale(dir, dir, MAX_VELOCITY);
  39. }
  40. //set velocity of our body(node) to the dir value
  41. body.setLinearVelocity(dir);
  42. };
  43. };
  44. exports.component = component;