Block disappearance timer

Godot Version

4.2.1

Question

Hello everyone! I’m making a block trap, its meaning is that when the player steps on it, after a while it disappears. I tried to use the code that ChatGpt wrote, but it is very controversial, here it is:

extends Area2D


var disappear_time: float = 2.0

var is_touched: bool = false

func _on_Area2D_body_entered(body):
    if body.is_in_group("player") and not is_touched:
        is_touched = true

        yield(get_tree().create_timer(disappear_time), "timeout")
        queue_free()  

func _ready():
    connect("body_entered", self, "_on_Area2D_body_entered")

I tried to use my own developments, but they failed. As a result, the block disappears, but it doesn’t care about the player. Here is the current code:

extends CharacterBody2D 


var disappear_time: float = 3.0


func _ready():
	
	$Timer.wait_time = disappear_time

	$Timer.start()


func _on_timer_timeout():
	queue_free()  


func _on_timer_ready():
	$Timer.start()

ChatGPT usually can’t keep up with GDScript changes, so it may be suggesting old solutions that don’t apply anymore in 4.x versions.
Its code here is almost correct though, if you do just a couple of changes it should work, see below. This is assuming that your Player node is assigned to a group “player” and your block is of type Area2D. This script should be attached to a block.

extends Area2D

var disappear_time: float = 2.0
var is_touched: bool = false

func _on_Area2D_body_entered(body):
    if body.is_in_group("player") and not is_touched:
        is_touched = true

        await get_tree().create_timer(disappear_time).timeout
        queue_free()  

func _ready():
    body_entered.connect(_on_Area2D_body_entered)

Thank you! I will check it out

It works, but it’s not physical (the player walks through it)

Area2D will not collide with your player, it is used to just detect if something has entered or exited its shape.
If you need this block to collide with the player, you can add this Area2D node as a child of a StaticBody2D that will represent the physical block that will collide with the player.
You just need to make the shape of the Area2D slightly bigger than the shape of the StaticBody2D, otherwise your player will never be able to reach it.
In the code, just change the
queue_free() to get_parent().queue_free() so that the block will disappear as a whole, not only the Area2D.
Your scene should look something like that:

1 Like

Thank you so much! Everything worked out!

1 Like