0 votes

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.

in Engine by (12 points)

2 Answers

0 votes

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

by (134 points)

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.

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

+1 vote
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

https://gotm.io/henry-software/pixelleveltest/

by (1,659 points)
edited by

Thank you! I'll try to use this.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.