Camera.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package view;
  2. import controller.KeyHandler;
  3. import model.entity.Entity;
  4. import javax.imageio.ImageIO;
  5. import java.awt.*;
  6. import java.io.IOException;
  7. public class Camera extends Entity {
  8. private KeyHandler keyH;
  9. private Image optionalPlayerImage;
  10. public final int screenX;
  11. public final int screenY;
  12. public Camera(GamePanel gamePanel, KeyHandler keyHandler){
  13. super(gamePanel);
  14. this.keyH = keyHandler;
  15. screenX = gp.screenWidth/2;
  16. screenY = gp.screenHeight/2;
  17. //getPlayerImage();
  18. setDefaultValues();
  19. }
  20. private void getPlayerImage(){
  21. try{
  22. optionalPlayerImage = ImageIO.read(getClass().getResourceAsStream("/sprites/bigrock.png"));
  23. }catch (IOException e){
  24. e.printStackTrace();
  25. }
  26. }
  27. public void setDefaultValues(){
  28. worldX = gp.tileSize * 23;
  29. worldY = gp.tileSize * 21;
  30. speed = 4;
  31. }
  32. public void move(int x, int y) {
  33. // 1. Calculate world dimensions
  34. int worldWidth = gp.maxWorldCol * gp.tileSize;
  35. int worldHeight = gp.maxWorldRow * gp.tileSize;
  36. // 2. Infer zoom factor
  37. float zoom = (float) gp.tileSize / gp.originalTileSize;
  38. // 3. Calculate visible screen size in world units
  39. float viewWidth = gp.screenWidth +zoom;
  40. float viewHeight = gp.screenHeight;
  41. float halfViewWidth = viewWidth / 2f;
  42. float halfViewHeight = viewHeight / 2f;
  43. // 4. Proposed new camera center position
  44. float newWorldX = worldX + x;
  45. float newWorldY = worldY + y;
  46. // 5. Clamp the camera to world bounds so no outside area is visible
  47. newWorldX = clamp(newWorldX, halfViewWidth, worldWidth - halfViewWidth);
  48. newWorldY = clamp(newWorldY, halfViewHeight, worldHeight - halfViewHeight);
  49. // 6. Update position
  50. worldX = (int) newWorldX;
  51. worldY = (int) newWorldY;
  52. }
  53. private float clamp(float value, float min, float max) {
  54. if (min > max) {
  55. // This happens when zoomed out so much that the view is larger than the world.
  56. // In that case, center the camera in the middle of the world.
  57. return (min + max) / 2f;
  58. }
  59. return Math.max(min, Math.min(max, value));
  60. }
  61. public void update(){
  62. if(keyH.upPressed){
  63. move(0, -speed);
  64. }
  65. if(keyH.downPressed){
  66. move(0, speed);
  67. }
  68. if(keyH.leftPressed){
  69. move(-speed, 0);
  70. }
  71. if(keyH.rightPressed){
  72. move(speed, 0);
  73. }
  74. }
  75. public void draw(Graphics2D g2){
  76. g2.setColor(Color.WHITE);
  77. g2.drawImage(optionalPlayerImage, screenX, screenY, gp.tileSize, gp.tileSize, null);
  78. }
  79. }