PlayerController.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { canvas } from '../Core.js';
  2. import { keys, KeyCode } from '../KeyboardInput.js';
  3. export class PlayerController {
  4. constructor(pawn, camera) {
  5. this.pawn = pawn;
  6. this.camera = camera;
  7. }
  8. onMouseDown(event) {
  9. let canvasBounds = canvas.getBoundingClientRect();
  10. let touchPoint = {
  11. x: event.clientX + this.camera.x - canvasBounds.width / 2,
  12. y: event.clientY + this.camera.y - canvasBounds.height / 2
  13. };
  14. let angle = this.getAngleFromPawn(touchPoint);
  15. if (event.buttons == 1 && event.button == 0) {
  16. this.pawn.thrustDirection(angle);
  17. }
  18. this.pawn.setAngle(angle);
  19. }
  20. onMouseMove(event) {
  21. let canvasBounds = canvas.getBoundingClientRect();
  22. let touchPoint = {
  23. x: event.clientX + this.camera.x - canvasBounds.width / 2,
  24. y: event.clientY + this.camera.y - canvasBounds.height / 2
  25. };
  26. let angle = this.getAngleFromPawn(touchPoint);
  27. if (event.buttons == 1 && event.button == 0) {
  28. this.pawn.thrustDirection(angle);
  29. }
  30. this.pawn.setAngle(angle);
  31. }
  32. onMouseUp(event) {
  33. this.pawn.stopThrust();
  34. }
  35. onTouchStart(event) {
  36. let canvasBounds = canvas.getBoundingClientRect();
  37. let touchPoint = {
  38. x: event.touches[0].clientX + this.camera.x - canvasBounds.width / 2,
  39. y: event.touches[0].clientY + this.camera.y - canvasBounds.height / 2
  40. };
  41. let angle = this.getAngleFromPawn(touchPoint);
  42. this.pawn.thrustDirection(angle);
  43. }
  44. onTouchMove(event) {
  45. let canvasBounds = canvas.getBoundingClientRect();
  46. let touchPoint = {
  47. x: event.touches[0].clientX + this.camera.x - canvasBounds.width / 2,
  48. y: event.touches[0].clientY + this.camera.y - canvasBounds.height / 2
  49. };
  50. let angle = this.getAngleFromPawn(touchPoint);
  51. this.pawn.thrustDirection(angle);
  52. }
  53. onTouchEnd(event) {
  54. event.preventDefault();
  55. this.pawn.stopThrust();
  56. }
  57. getAngleFromPawn(touchPoint) {
  58. return Math.atan2(touchPoint.y - this.pawn.position.y, touchPoint.x - this.pawn.position.x);
  59. }
  60. }