How to connect a button to a door?

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

I’m very new to coding in general, but I can’t figure this out for the life of me.

I have a Button.tscn and a Door.tscn. I’m trying to have the door change sprites when the player stands on the button.

Inside the I have this:

const DOOR = preload("res://World/Door.tscn")
onready var Door = DOOR.instance()

func _on_PlayerDetection_body_entered(body):
	var DoorSprite = Door.get_node("Sprite")
    DoorSprite.frame = 1

I have no idea what I’m missing here. There’s no error or anything, but the door simply won’t change sprites.

You instanced a door by code, but did you add it to some other node with add_child? Cause i dont see that in the code you shared. Or are you trying to change the sprite of an already placed door somewhere in the scene tree?

p7f | 2020-09-05 21:13

I assume DoorSprite.frame = 1 is the a sprite of the door opened. So when the player collides with the area the door opens.

Are you sure you have your collisions correct?
You can try putting a print statement in func _on_PlayerDetection_body_entered . Something like print(“The door is open”). This will tell you if your player is actually colliding with the area.

Also, I’m not sure were you are handling the script. I would have it contained in the Door scene. That way all the logic of the door is held in it’s own scene and you don’t have to signal up to another script and then to call down to the door scene.

Door Scene:
Root - Door (Node2d)
-PlayerDetectZone (Area2D) (This is also where you would set your collision Mask to the player’s layer)
–CollisionShape2d Script

extends KinematicBody2D

onready var playerDectionZone = $PlayerDetectZone

func _physics_process(delta):

func seek_player():
	if playerDectionZone.can_see_player():
             DoorSprite.frame = 1
             DoorSprite.frame = 0 #if you want the door to close when play is out of area script

extends Area2D

var player = null

func can_see_player():
	return player != null #True or false if player is in area

#the next two functions are signals that you connect from the CollisionShape2D to itself, body_entered and body_exited. This will fire a signal when KinematicBody enters the area. It will only fire if the collision Mask are setup properly.

func _on_PlayerDetectZone_body_entered(body):
	player = body

func _on_PlayerDetectZone_body_exited(_body):
	player = null

Now you can place the door scene anywhere and how ever many times you want without have to find the node in another script.

RichmondGames | 2020-09-06 14:55