Camera.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { Point } from "./spatial/Point.js";
  2. export class Camera {
  3. constructor() {
  4. this.position = new Point(0, 0)
  5. this.angle = 0;
  6. this.scale = new Point(1, 1)
  7. this.canvasBounds = null;
  8. }
  9. update(delta) {
  10. // let frequency = 0.125;
  11. // this.angle += Math.PI / 64;
  12. // if(this.angle >= (2 / frequency) * Math.PI) {
  13. // this.angle = 0;
  14. // }
  15. // this.position.x = this.canvasBounds.width / 8 * Math.cos(frequency * this.angle);
  16. // this.position.y = this.canvasBounds.width / 8 * Math.sin(frequency * this.angle);
  17. }
  18. drawAtCamera(ctx, scaledCanvas, drawFunc) {
  19. this.canvasBounds = scaledCanvas.bounds;
  20. ctx.save();
  21. ctx.translate(-this.position.x, -this.position.y);
  22. drawFunc(ctx, scaledCanvas);
  23. ctx.restore();
  24. }
  25. draw(ctx, scaledCanvas, drawFunc) {
  26. this.canvasBounds = scaledCanvas.bounds;
  27. ctx.save();
  28. ctx.translate(-this.position.x + Math.round(this.canvasBounds.width / 2), -this.position.y + Math.round(this.canvasBounds.height / 2));
  29. ctx.scale(this.scale.x, this.scale.y)
  30. drawFunc(ctx, scaledCanvas);
  31. ctx.restore();
  32. }
  33. screenToWorld(touchPosition) {
  34. let position = new Point(touchPosition.x,touchPosition.y)
  35. position.x += this.position.x - Math.round(this.canvasBounds.width / 2)
  36. position.y += this.position.y - Math.round(this.canvasBounds.height / 2)
  37. position.scale(1/this.scale.x, 1/this.scale.y)
  38. return position
  39. }
  40. worldToScreen(charPosition) {
  41. let position = new Point(charPosition.x, charPosition.y)
  42. position.scale(this.scale.x, this.scale.y)
  43. position.x += -this.position.x + Math.round(this.canvasBounds.width / 2)
  44. position.y += -this.position.y + Math.round(this.canvasBounds.height / 2)
  45. return position
  46. }
  47. }