Godot Version
v4.2.stable.official [46dc27791]
Question
I’m trying to write code that sets the camera’s limits based on boundaries given in a different node, but all the methods I’ve tried to do so cause the game to crash. The documentation is rather confusing and doesn’t help much either.
Here’s all the methods I tried to get it to work (they all crash the game):
set_limit("SIDE_LEFT", room_properties.left_border)
set_limit(SIDE_LEFT, room_properties.left_border)
set_limit(0, room_properties.left_border)
set_limit(limit_left, room_properties.left_border)
set_limit("limit_left", room_properties.left_border)
room_properties
is a separate node (@onready var room_properties = %"Room Properties"
) that stores the camera bounds via export variables.
Here’s the full camera.gd script (most of the code isn’t relevant to my issue, but I’m still including it for the bigger picture):
extends Camera2D
@onready var player = %Player
@onready var room_properties = %"Room Properties"
# pixels/second, should be faster than player speed
var max_speed = 2000
# acceleration in pixels/second
var acceleration = 10000
var desired_speed = 0
var current_speed = 0
var target_position = 0
# Various methods I tried using to have camera limit set to variables
set_limit("SIDE_LEFT", room_properties.left_border)
set_limit(SIDE_LEFT, room_properties.left_border)
set_limit(0, room_properties.left_border)
set_limit(limit_left, room_properties.left_border)
set_limit("limit_left", room_properties.left_border)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta):
if player.alive:
if abs(player.velocity.x) > player.SPEED:
target_position = player.position.x + (1200 * player.directionX)
elif abs(player.velocity.x) == 0:
target_position = player.position.x
elif abs(player.velocity.x) < player.SPEED:
target_position = player.position.x + (670 * player.directionX)
else:
target_position = player.position.x + (800 * player.directionX)
var distance_to_player = abs(target_position - position.x)
if abs(player.velocity.x) == 0:
desired_speed = 0
else:
desired_speed = min(distance_to_player, max_speed) # calculate this however you like
current_speed = move_toward(current_speed, desired_speed, acceleration*delta)
position.x = move_toward(position.x, target_position, current_speed*delta)
position.y = player.position.y