Camera.js 1.9 KB

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