I’m a beginner who is following the tutorial from Brackeys, then I want to add a mechanic where when the player dies the player cannot move. But I experienced difficulties when trying to create the code. In this code is_alive keeps returning true which should be false when passing the enemy
extends CharacterBody2D
const SPEED = 300.0
const JUMP_VELOCITY = -400.0
var is_alive: bool = true
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
func _physics_process(delta):
if not is_alive:
return
if not is_on_floor():
velocity.y += gravity * delta
if Input.is_action_just_pressed("ui_accept") and is_on_floor():
velocity.y = JUMP_VELOCITY
var direction = Input.get_axis("ui_left", "ui_right")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
func die():
is_alive = false
print("Dead")
print(is_alive)
func _process(delta):
print(is_alive)
pass
The second line creates a new player, one that doesn’t exist in the scene tree so it can’t do anything (but die). I see a story with the first line, you do not need to know the path to the player, _on_body_entered gives you body which is the thing entering the area, if it’s the player your want to use .die() on them.
Try this:
func _on_body_entered(body):
if body.name == "Player":
body.die() # body is player
Engine.time_scale= 0.5
body.get_node("CollisionShape2D").queue_free()
timer.start()