How do I set the camera 2D boundary?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By miyatora

Hello!
I’m working on a mobile project.
If I set the rectangle area and drag the screen, I hope the camera will move only in there.
How do you visually represent an rectangle and how to make the camera move only inside the box?
And what should I do to keep the camera from bouncing off rather than stopping suddenly?
Thank you in advance.

:bust_in_silhouette: Reply From: AuthorSan

You can use Camera’s Limit Property in the inspector. You can set it manually or through the code.

I’ve already used it, but if the camera goes to the corner, it won’t move well, so I’m looking for another way.
Thank you for your answer.

miyatora | 2020-08-24 12:13

What do you mean by it won’t move well? Can you elaborate?

AuthorSan | 2020-08-24 15:32

:bust_in_silhouette: Reply From: rakkarage
func _cameraUpdate() -> void:
	var map := mapBounds()
	var world := _worldBounds().grow(-_back.cell_size.x)
	if not world.intersects(map):
		_cameraSnap(_camera.global_position + _constrainRect(world, map))
	else:
		emit_signal("updateMap")

here is another way…

func _mapSize() -> Vector2:
	return rect.size * _back.cell_size

func mapBounds() -> Rect2:
	return Rect2(-_camera.global_position, _mapSize())

func _worldSize() -> Vector2:
	return size * _camera.zoom

func _worldBounds() -> Rect2:
	return Rect2(Vector2.ZERO, _worldSize())

get map bounds and world bounds and constrain one based on other

static func _constrainRect(world: Rect2, map: Rect2) -> Vector2:
	return _constrain(world.position, world.end, map.position, map.end)

static func _constrain(minWorld: Vector2, maxWorld: Vector2, minMap: Vector2, maxMap: Vector2) -> Vector2:
	var delta := Vector2.ZERO
	if minWorld.x > minMap.x: delta.x += minMap.x - minWorld.x
	if maxWorld.x < maxMap.x: delta.x -= maxWorld.x - maxMap.x
	if minWorld.y > minMap.y: delta.y += minMap.y - minWorld.y
	if maxWorld.y < maxMap.y: delta.y -= maxWorld.y - maxMap.y
	return delta

if you drag the generated map off screen (or just about (thanks grow) off screen) it snaps back on

Thank you! I’ll try to use this.

miyatora | 2020-08-24 23:22