How to remove/kill instantiated child/enemy
Asked Answered
S

2

1

Hey, I've been trying to get this piece of code to work. I am trying to make a game where you can kill an enemy with your mouse click. I have tried it by using signals but i am not sure i am doing it right. Here is my code:
From my main scene:


extends Node



func _ready():
	pass 
	
var enemy = preload ("res://enemy.tscn")


func _on_timer_timeout():
	var new_spawn = enemy.instantiate()
	var rng = RandomNumberGenerator.new()
	var randomx = rng.randf_range(0.0, 1152.0)
	var randomy= rng.randf_range(50.0, 600.0)
	new_spawn.position = Vector2(randomx, randomy)
	add_child(new_spawn)
	print("spawn")


func _on_enemy_hit():
	if is_instance_valid(enemy):
		enemy.queue_free()
	print("delete")

from my enemy scene:


extends CharacterBody2D

const SPEED = 300.0
const JUMP_VELOCITY = -400.0


var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")


func _physics_process(delta):
	



	if not is_on_floor():
		velocity.y += gravity * delta
	
	move_and_slide()

var mouse_hit
func _on_mouse_entered():
	mouse_hit = true

func _on_mouse_exited():
	mouse_hit = false
	
var raak
signal hit
func _input(event):
	if mouse_hit and Input.is_action_pressed("mouse_left"):
		print("raak")
		hit.emit()

Can somebody help me out

Santana answered 21/2 at 12:0 Comment(0)
C
0

So close! You need to connect your _on_enemy_hit function to the hit signal. Whenever you emit the hit signal, then the _on_enemy_hit function will be called.

hit.connect(_on_enemy_hit)

You can connect the signal and function using the editor too, see the Using signals docs.

Colonel answered 21/2 at 20:0 Comment(0)
S
0

Colonel
Thx for the reply. But I can't figure out where to put the line hit.connect(_on_enemy_hit).
I get this error when I place it in the main scene : Line 22:Identifier "hit" not declared in the current scope.
I get this error when I place it in the enemy scene: Line 28:Identifier "_on_enemy_hit" not declared in the current scope.
Can you help me out?

EDIT:
I have figured out how to connect it through: https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html#connecting-a-signal-in-the-editor.
But now it works only with the original enemy child note. In my game I spawn new enemies by instantiating the enemy scene. However the signal does not seem to work with these instantiated scenes.

Santana answered 26/2 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.