Input.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. "atomic component";
  2. var component = function(self) {
  3. var yaw = 0;
  4. var pitch = 0;
  5. var node = self.node;
  6. // Movement speed as world units per second
  7. var MOVE_SPEED = 20.0;
  8. // Mouse sensitivity as degrees per pixel
  9. var MOUSE_SENSITIVITY = 0.1;
  10. //start function called when component attached to the node, after constructor
  11. self.start = function() {
  12. Atomic.audio.listener = node.getComponent("SoundListener");
  13. };
  14. //update function called once per each frame
  15. self.update = function(timeStep) {
  16. // Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
  17. var mouseMove = Atomic.input.mouseMove;
  18. yaw += MOUSE_SENSITIVITY * mouseMove[0];
  19. pitch += MOUSE_SENSITIVITY * mouseMove[1];
  20. if (pitch < -90)
  21. pitch = 90;
  22. if (pitch > 90)
  23. pitch = 90;
  24. // Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
  25. node.rotation = QuatFromEuler(pitch, yaw, 0.0);
  26. // Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
  27. if (Atomic.input.getKeyDown(Atomic.KEY_W))
  28. node.translate([0, 0, MOVE_SPEED * timeStep]);
  29. if (Atomic.input.getKeyDown(Atomic.KEY_S))
  30. node.translate([0, 0, -MOVE_SPEED * timeStep]);
  31. if (Atomic.input.getKeyDown(Atomic.KEY_D))
  32. node.translate([MOVE_SPEED * timeStep, 0, 0]);
  33. if (Atomic.input.getKeyDown(Atomic.KEY_A))
  34. node.translate([-MOVE_SPEED * timeStep, 0, 0]);
  35. };
  36. };
  37. //Math function to get Quaternion from Euler angles
  38. function QuatFromEuler(x, y, z) {
  39. var M_PI = 3.14159265358979323846264338327950288;
  40. var q = [0, 0, 0, 0];
  41. x *= (M_PI / 360);
  42. y *= (M_PI / 360);
  43. z *= (M_PI / 360);
  44. var sinX = Math.sin(x);
  45. var cosX = Math.cos(x);
  46. var sinY = Math.sin(y);
  47. var cosY = Math.cos(y);
  48. var sinZ = Math.sin(z);
  49. var cosZ = Math.cos(z);
  50. q[0] = cosY * cosX * cosZ + sinY * sinX * sinZ;
  51. q[1] = cosY * sinX * cosZ + sinY * cosX * sinZ;
  52. q[2] = sinY * cosX * cosZ - cosY * sinX * sinZ;
  53. q[3] = cosY * cosX * sinZ - sinY * sinX * cosZ;
  54. return q;
  55. }
  56. exports.component = component;