How do I code my Area2D to do damage to my player character

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

How do I make my player take damage?

Hey. I’m currently working on my finals and have run into an issue. In my 2D platformer I want my character to take damage from a beam to light. I’ve made the beam of light a Area2D Node, but I’m not quite sure how to make it deal damage to my player character.

Here’s what my player code looks like

extends KinematicBody2D

signal health_updated(health)

signal killed()

var velocity = Vector2(0,0)

const SPEED = 375

const GRAVITY = 30

const JUMPFORCE = -1000

export (float) var max_health = 100

onready var health = max_health setget _set_health

# warning-ignore:unused_argument

func _physics_process(delta):


	velocity.x = SPEED


	$AnimatedSprite.flip\_h = false


	velocity.x = -SPEED


	$AnimatedSprite.flip\_h = true



if not is\_on\_floor():


velocity.y = velocity.y + GRAVITY

if\_action\_just\_pressed("jump") and is\_on\_floor():

	velocity.y = JUMPFORCE

velocity = move\_and\_slide(velocity,Vector2.UP)

velocity.x = lerp(velocity.x,0,0.2)

func damage(amount):

\_set\_health(health - amount)


func kill():\


func _set_health(value):

var prev\_health = health

health + clamp(value, 0, max\_health)

if health != prev\_health:

	emit\_signal("health\_updated", health)

	if health == 0:



If it’s a mess (which it probably is), it’s because I’ve used multiple Youtube tutorials for this project so far.

How do I make the Area2D Node deal damage?

:bust_in_silhouette: Reply From: exuin

Put a script on the Area2D. Connect the body_entered signal from the Area2D to that script. Check if the body is the player and then call the set health function.

Alright. I’ve done the first part. How do I call the set_health function and get it to take away some of my players health?

Phantomist | 2022-12-10 22:48


Usually functions with underscore in front of the name are meant to private (not called from other script) though.

exuin | 2022-12-11 06:31

Alright. How should I go about fixing this? Do I remove the underscore? Thank you so much for the responses.

Phantomist | 2022-12-12 03:28

Yeah you can remove the underscore

exuin | 2022-12-12 03:52

Alright. I’m trying to call the function. I’ve put the function into a scene that is globally loaded. Whenever I try and run it though, it says ”Invalid call. Nonexistent function ‘set_health’ in base ‘TileMap’. What do I need to do?

Phantomist | 2022-12-14 20:55

make sure to check that the body is the player.

exuin | 2022-12-14 21:20

How do I do that?

Phantomist | 2022-12-14 23:43

if == "Whatever you named the player"

exuin | 2022-12-15 17:17

Where do I put this on my script? Do I put it above or below the _on_Area2D_body_entered?

Phantomist | 2022-12-16 03:48