0 votes

Hi,

I'm new in Godot and have a problem that I can't solve. I have a project where player 1 or player 2 play the same level not at the same time. So, in order to do that, I instanced my Player 1 or Player 2 scene to my level 1 (named "world2). It works, but know, my camera script that make follow the player only on the x axis doesn't work anymore, because the camera is unable to find the node Player 1 or Player 2 (I get a null instance).

The scripts in my world scene look like that (for player2):

extends Node2D

onready var player2 = ("Root/world2/Player2")

func _ready():
   var Player2 = preload("res://Scènes/Player2.tscn").instance()
   add_child(Player2)

And the script of my camera 2D (was working before with the node player2 as a child of the world):

extends Camera2D

onready var player2 = get_node ("Player2")

func _process (delta):

    position.x = player2.position.x

I try to write also the absolute path of Player 2 but without success... Sorry if it's a basic question but I can't figure out =/...

Godot version 3.3.2
in Engine by (12 points)

1 Answer

0 votes

Hi there. First of all there's a mistake in your script. This line:

onready var player2 = ("Root/world2/Player2")

The player2 variable is set to be a string. Looks like a path to the original node. Then in the _ready function you set the same variable again and you use preload to load the scene.

Try this way:

onready var player_two_scene = preload("res://Scènes/Player2.tscn")

func _ready():
    var player_two = player_two_scene.instance()
    add_child(player_two)

It would help if you provides the tree structure from your project.

EDIT: I see now that it's not the same variable you set. Consider renaming the variables to avoid mistakes. Anyway my answer remains the same for now. :)

by (80 points)
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.