I can't disable player movement when he dies

Godot Version

4.2.2

Question

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

Does the player reset, like through change_scene_to_file? Does any other script touch is_alive?

1 Like

Yes player can reset to spawnpoint, No other script touches is_alive

This is the code i used for KillZone :

extends Area2D

@onready var timer = $Timer
#@onready var player = %Player
@onready var playerscript = preload("res://Scenes/player.tscn").instantiate()

func _on_body_entered(body):
	#print("You died!!")
	playerscript.die()
	Engine.time_scale= 0.5
	body.get_node("CollisionShape2D").queue_free()
	timer.start()
	
	
	
func _on_timer_timeout():
	get_tree().reload_current_scene()
	Engine.time_scale = 1

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()
1 Like

Thanksss, it works :+1: :+1:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.