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:
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)
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: