Thanks for the Reply, i am happy to help :)
I have broken the code down to make it more clear what is happening.
I also fixed an issue by now using global_position
instead of position
.
Use this code after you changed the position of the Camera2D
this code only works correctly when "Camera2D.anchor_mode" is Drag Center.
first we get the viewport size and divide it by 2 to get the viewport's center.
var viewport_half_x = get_viewport_rect().size.x/2
var viewport_half_y = get_viewport_rect().size.y/2
then we offset the limits to acount for the viewport size
var new_limit_left = limit_left+viewport_half_x
var new_limit_top = limit_top+viewport_half_y
var new_limit_right = limit_right-viewport_half_x
var new_limit_bottom = limit_bottom-viewport_half_y
lastly, we clamp the Camera2D's position between the new limits.
var new_x = clamp(global_position.x, new_limit_left,new_limit_right)
var new_y = clamp(global_position.y, new_limit_top,new_limit_bottom)
global_position = Vector2(new_x,new_y)
Final code written in an function:
func snap_in_limit():
#this code only works correctly when "Camera2D.anchor_mode" is Drag Center.
#first we get the viewport size and divide it by 2 to get the viewport's center.
var viewport_half_x = get_viewport_rect().size.x/2
var viewport_half_y = get_viewport_rect().size.y/2
#we offset the limits to acount for the viewport size
var new_limit_left = limit_left+viewport_half_x
var new_limit_top = limit_top+viewport_half_y
var new_limit_right = limit_right-viewport_half_x
var new_limit_bottom = limit_bottom-viewport_half_y
#clamp the Camera2D's position between the new limits.
var new_x = clamp(global_position.x, new_limit_left,new_limit_right)
var new_y = clamp(global_position.y, new_limit_top,new_limit_bottom)
global_position = Vector2(new_x,new_y)
Feel free to ask if anything is unclear/not working properly.