¿How do i remove health using raycast?

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

Sorry if i cant express myself good in the title, but im making a little fps to practice with godot and im trying to make the shooting mechanic, i have a raycast and a kinematic body called “bag” with a variable called health, i want to make if the raycast detects a group called “enemies” in which the bag is, and if Input left_click pressed i want to substract 1 from that health variable, but i dont know how to do it, thanks for any help.

:bust_in_silhouette: Reply From: timothybrentwood
onready var shooting_ray_cast = get_node("RayCast") # where ever your RayCast is located

func _input(event: InputEvent) -> void:
    if event.is_action_pressed("left_click"): # replace with whatever your left click is in Project Settings
        shooting_ray_cast.force_raycast_update()
        var colliding_object = shooting_ray_cast.get_collider()
        if not is_instance_valid(colliding_object): # colliding_object is queued for deletion or does not exist
			pass
		elif colliding_object.get("health"):
			colliding_object.health = colliding_object.health - 1

This code should accomplish what you want to do, it’s flawed though. Ideally you’d want to emit a signal when you get a valid collision_object and let the collision_object do the work of reducing its own health. You probably also want to create a Gun object and just call Gun.fire() when you get a left click input, then let the Gun object figure out if it can fire (isn’t reloading, etc.), calculate the damage done, etc.

Thanks for the answer, it worked!

Arielrandal | 2021-06-03 17:31