2
\$\begingroup\$

I'm totally new to Godot 3 engine. I want a game with static camera, so it can't smoothly follow player. I made an Area2D signal when_body_entered witch teleports main character to next area of map. Now I need to know how to move the camera (in Vector2 or just Y axis) when player enters the area.

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

Multiple cameras

Have multiple Camera2D. Then on the handler for "body_entered" signal of your Area2D you can set Camera.current = true for the Camera2D of the next room (areas of the map). And set current to false for the prior camera.

Alright, if you are going to have references to the cameras in your script, you may instead export some NodePaths for them. Something like this:

export var old_cam_path:NodePath
export var new_cam_path:NodePath

func when_body_entered(body:Node) -> void:
    get_node(new_cam_path).current = true
    get_node(old_cam_path).current = false

    # Also teleport the player character

Now, you should be able to select the old and the new camera in the inspector panel.


Teleporting Camera

Alright, but we don't want to change cameras, we want to move the camera. Well, add some Position2D nodes to mark the position for the camera, and then we can do this:

export var cam_path:NodePath
export var cam_target_path:NodePath

func when_body_entered(body:Node) -> void:
    var cam := get_node(cam_path) as Camera2D
    var cam_target := get_node(cam_target_path) as Position2D
    cam.position = cam_target.position

    # Also teleport the player character

By the way, you can use the same approach to teleport the player character.


I'll also remind you that you can use the collision layers to filter what the Area2D detects. Also, a common approach is to use groups to discern between the bodies. You can add groups to nodes in the Node panel on the Groups tab. Then in code use body.is_in_group("group_name") to check.


Traveling Camera

Another thing you can do with this is to tween over time the camera position instead of changing it instantly. To do that we can use a Tween node. Which in this case I will go ahead and create from code instead of adding it in the editor:

export var cam_path:NodePath
export var cam_target_path:NodePath

var tween:Tween

func _ready() -> void:
    tween = Tween.new()
    add_child(tween)

func when_body_entered(body:Node) -> void:
    var cam := get_node(cam_path) as Camera2D
    var cam_target := get_node(cam_target_path) as Position2D

    var seconds:float = 1.0
    tween.interpolate_property(cam, "position", cam.position, cam_target.position, seconds)
    tween.start()

    # Also teleport the player character

Here we are telling the Tween to move the "position" of the camera, from the current value of camera.position to the current value of camera_target.position, in the span of seconds.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .