camera.js 1.3 KB

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