Camera.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. class Camera {
  2. constructor() {
  3. this.position = { x: -100, y: -100 };
  4. this.viewBox = { x: 100, y: 100, width: 600, height: 400 };
  5. }
  6. init(canvas) {
  7. this.viewBox.x = canvas.width / 3;
  8. this.viewBox.y = canvas.height / 3;
  9. this.viewBox.width = canvas.width - 2 * this.viewBox.x;
  10. this.viewBox.height = canvas.height - 2 * this.viewBox.y;
  11. this.position = { x: canvas.width / 2, y: canvas.height / 2 };
  12. }
  13. update(canvas, player, delta) {
  14. this.followPlayer(player, delta);
  15. }
  16. handleResize(canvas) {
  17. this.viewBox.x = canvas.width / 3;
  18. this.viewBox.y = canvas.height / 3;
  19. this.viewBox.width = canvas.width - 2 * this.viewBox.x;
  20. this.viewBox.height = canvas.height - 2 * this.viewBox.y;
  21. }
  22. followPlayer(player) {
  23. var truePos = { x: 0, y: 0 };
  24. truePos.x = this.position.x + player.position.x;
  25. truePos.y = this.position.y + player.position.y;
  26. if (truePos.x <= this.viewBox.x) {
  27. this.position.x -= truePos.x - this.viewBox.x;
  28. }
  29. if (player.position.x + this.position.x >= this.viewBox.x + this.viewBox.width) {
  30. this.position.x += (this.viewBox.x + this.viewBox.width) - truePos.x;
  31. }
  32. if (truePos.y <= this.viewBox.y) {
  33. this.position.y -= truePos.y - this.viewBox.y;
  34. }
  35. if (player.position.y + this.position.y >= this.viewBox.y + this.viewBox.height) {
  36. this.position.y += (this.viewBox.y + this.viewBox.height) - truePos.y;
  37. }
  38. }
  39. }