#[Solved] Can you get a property from an overlapping Node?

5 messages · Page 1 of 1 (latest)

earnest finch
#

So I'm trying to make an Asteroid game for practice, and one of the things I want to do is that every time an asteroid enters the ship's hurtbox, the ship will get the enemy_attack variable from the asteroid to calculate the damage it'll receive.

This is what I've done so far. First is the take_damage() function in the ship's script:

func take_damage() -> void:
    var enemy := hurt_box.get_overlapping_bodies()
    var damage : int = round(enemy.enemy_attack / defense)
    health = health - damage
    health_bar.value = health
    if health <= 0:
        get_tree().paused

And here is the asteroid's script:

extends CharacterBody2D

@onready var asteroid: CharacterBody2D = %Asteroid
@onready var player: CharacterBody2D = %Player

@export var enemy_attack := 5
var speed = 300.0

func _physics_process(delta: float) -> void:
    var direction := global_position.direction_to(player.global_position)
    velocity = direction.normalized() * speed
    move_and_slide()

But right now, I receive the error "Cannot find property 'enemy_attack' on base Array[Node2D]"

The idea is that, if everything works, then the ship will get the enemy_attack from the asteroid and use it to calculate the damage it'll take. In this case, it would take 5/3 = 1.67 (rounded up to 2 damage).

The reason why I did this is because I'm thinking what if I want to make different asteroids with different enemy_attack values. It might be helpful to scale the game up later on (or reuse the code in other games that also features waves of different enemies)

mortal spindle
#

You’re on the right track. get_overlapping_bodies returns an array (https://docs.godotengine.org/en/stable/classes/class_area2d.html#class-area2d-method-get-overlapping-bodies), so you likely need to look at each element to see if it is an enemy, and then poke at its properties, e.g.

enemies[0].enemy_attack```
(and check the array isn’t empty, etc… consider using signals instead)
earnest finch
#

Yeah, I tried to use enemy[0].enemy_attack, but I ran into the problem that the array is empty at the beginning of the game, so it crashes. Not entirely sure how to fix that...

As for using signals...how do you get a node via signals? I thought it just lets you know if something happens?

glacial pumice
earnest finch
#

Alright, now it works! The final code is:

func take_damage() -> void:
    var enemy : Node = hurt_box.get_overlapping_bodies().front()
    if enemy == null:
        return
    else:
        var damage : int = round(enemy.enemy_attack / defense)
        health = health - damage
        health_bar.value = health

Thank you everyone!