Hello, I am completely new to godot, and I need help with some code for changing scenes. I have an area 2d with a collisionpolygon for the shape, and I would like to know how to make it so when a characterbody2d enters it, it switches the scene to a new one. Also, I would like to know how to name scenes. My current scene is a tab that is titled "unnamed". Thank you! It is in 4.1.2 I think.
You could use the function func _on_body_entered()
to check if a PhysicsBody2D just entered and if you want it to only switch if the body is the Player then you can just check in the function if the body is a CharacterBody2D
Example code:
func _on_body_entered(body):
if body == CharacterBody2D:
get_tree().change_scene_to_file("res://wherever-your/file/is.tscn")
Hope this helps.
Aeromedical you can change the scene name when saving it and you can also change it in the file viewer, right-click the scene and click rename.
Monoacid Hey, this isnt working. Do I need to do anything to connect a scene to the scene tree?
Aeromedical what is your CharacterBody2D called? If you have it named something else, the above code won't work. Marder has it right though. You can also "preload" the scene as a variable for an abstraction shortcut. Make sure to connect your signal as well to the object executing the script.
To illustrate that alternate method:
const _myScene = preload("scenepathhere.file")
func _on_body_entered(body): ## make sure to connect this in editor or code first
if body.name == "YourBodyNameHere":
get_tree().change_scene_to(_myScene)
Galcha Do I connect it in the code by just using var body = CharacterBody2D
?
Aeromedical if that is the name of that body, yes.
It probably needs to be:
var body = $CharacterBody2D
Pirbhai Should I have a @onready ?
Tupler "#p134611 Because this is my current code
`extends Area2D
@onready var body = $CharacterBody2D
const _myScene = preload("res://the_walled_city.tscn")
func on_body_entered(body): ## make sure to connect this in editor or code first
if body.name == "MainCharacter":
get_tree().change_scene_to(myScene)`
Aeromedical
If you want to define a variable named "body" for the complete script, yes, that's what you need. But I think the problem is something else here. You have a parameter named "body" in your_ on_body_entered function. But this "body" is not automatically the same as the variable you defined on top (so your $CharacterBody2D). It is whatever is passed to that function, and that depends on what the function is connected to. So I would be careful to call them both the same thing.
Can you check if the function is called at all? So if the event just doesn't trigger or if the if condition is somehow not met? Maybe just have a breakpoint or print directly before the if statement.
© 2022 - 2024 — McMap. All rights reserved.