camera.js 1.4 KB

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