| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package view;
- import controller.KeyHandler;
- import model.entity.Entity;
- import javax.imageio.ImageIO;
- import java.awt.*;
- import java.io.IOException;
- public class Camera extends Entity {
- private KeyHandler keyH;
- private Image optionalPlayerImage;
- public final int screenX;
- public final int screenY;
- public Camera(GamePanel gamePanel, KeyHandler keyHandler){
- super(gamePanel);
- this.keyH = keyHandler;
- screenX = gp.screenWidth/2;
- screenY = gp.screenHeight/2;
- //getPlayerImage();
- setDefaultValues();
- }
- private void getPlayerImage(){
- try{
- optionalPlayerImage = ImageIO.read(getClass().getResourceAsStream("/sprites/bigrock.png"));
- }catch (IOException e){
- e.printStackTrace();
- }
- }
- public void setDefaultValues(){
- worldX = gp.tileSize * 23;
- worldY = gp.tileSize * 21;
- speed = 4;
- }
- public void move(int x, int y) {
- // 1. Calculate world dimensions
- int worldWidth = gp.maxWorldCol * gp.tileSize;
- int worldHeight = gp.maxWorldRow * gp.tileSize;
- // 2. Infer zoom factor
- float zoom = (float) gp.tileSize / gp.originalTileSize;
- // 3. Calculate visible screen size in world units
- float viewWidth = gp.screenWidth +zoom;
- float viewHeight = gp.screenHeight;
- float halfViewWidth = viewWidth / 2f;
- float halfViewHeight = viewHeight / 2f;
- // 4. Proposed new camera center position
- float newWorldX = worldX + x;
- float newWorldY = worldY + y;
- // 5. Clamp the camera to world bounds so no outside area is visible
- newWorldX = clamp(newWorldX, halfViewWidth, worldWidth - halfViewWidth);
- newWorldY = clamp(newWorldY, halfViewHeight, worldHeight - halfViewHeight);
- // 6. Update position
- worldX = (int) newWorldX;
- worldY = (int) newWorldY;
- }
- private float clamp(float value, float min, float max) {
- if (min > max) {
- // This happens when zoomed out so much that the view is larger than the world.
- // In that case, center the camera in the middle of the world.
- return (min + max) / 2f;
- }
- return Math.max(min, Math.min(max, value));
- }
- public void update(){
- if(keyH.upPressed){
- move(0, -speed);
- }
- if(keyH.downPressed){
- move(0, speed);
- }
- if(keyH.leftPressed){
- move(-speed, 0);
- }
- if(keyH.rightPressed){
- move(speed, 0);
- }
- }
- public void draw(Graphics2D g2){
- g2.setColor(Color.WHITE);
- g2.drawImage(optionalPlayerImage, screenX, screenY, gp.tileSize, gp.tileSize, null);
- }
- }
|