extends Camera2D class_name RoomCamera # Splits the level into screen-sized rooms and snaps to whichever room the # target is in, VVVVVV style: the camera never scrolls, it just cuts to the # next screen when the target crosses a room border. # # Room (0, 0) has its top-left corner at the level's origin, room (1, 0) is the # screen to its right, and so on. Rooms with negative coordinates work too. # Our tiles are 32x32, so one room is exactly 20x15 tiles. const ROOM_SIZE := Vector2(640, 480) # How far (in pixels) the target must get past a border before we switch rooms, # so standing right on a border doesn't flicker between the two screens. const SWITCH_MARGIN := 4.0 # The node to follow, usually the Player. @export var target: Node2D var room := Vector2i.ZERO func _ready() -> void: # Our position is the room's top-left corner, so the room fills the screen. anchor_mode = Camera2D.ANCHOR_MODE_FIXED_TOP_LEFT position_smoothing_enabled = false # Run after the player has moved this frame. process_physics_priority = 100 make_current() if target != null: room = room_at(_focus()) _snap_to_room() func _physics_process(_delta: float) -> void: if target == null: return var newRoom := _room_with_margin(_focus()) if newRoom != room: room = newRoom _snap_to_room() # The point to keep on screen. A target can say where that is with a # get_camera_focus() method (the Player does, so we follow it through tubes). func _focus() -> Vector2: if target.has_method(&"get_camera_focus"): return target.get_camera_focus() return target.global_position # Which room a point in the level is in. static func room_at(point: Vector2) -> Vector2i: return Vector2i((point / ROOM_SIZE).floor()) # The rectangle a room covers, in level coordinates. static func room_rect(roomCoords: Vector2i) -> Rect2: return Rect2(Vector2(roomCoords) * ROOM_SIZE, ROOM_SIZE) # Like room_at(), but sticks with the current room until the point is # SWITCH_MARGIN pixels past its border. func _room_with_margin(point: Vector2) -> Vector2i: var current := room_rect(room).grow(SWITCH_MARGIN) if current.has_point(point): return room return room_at(point) func _snap_to_room() -> void: global_position = Vector2(room) * ROOM_SIZE # Physics interpolation is on in this project, which would otherwise slide # the camera between the two rooms for a frame. Make it a clean cut. reset_physics_interpolation() reset_smoothing()