How do I detect 'if_colliding()' with an enemy KinematicBody2D when using Arrays?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Corruptinator
:warning: Old Version Published before Godot 3 was released.

Hello! I am currently working on a prototype for a 2D Platformer hack ‘n’ slash type game and I am figuring out how to get the enemy nodes to work…

I wanted to find a way to let the enemies hurt the player if it makes contact/collision with the latter.

I found out that this function: get_collider() allows the player KinematicBody2D to collect the body of what is colliding/detecting with the other object.

So with that in mind, is there a way to tell by using the array function to see if the player is colliding with an enemy?

I only see through two options but not sure if this works:

I could up an “Enemy” Node2D to store multiple enemies within and then use the function get_children() to get the entire array list of what is within the Node2D object.

The other is the same “Enemy” Node2D but this time it uses get_meta_list() to work as an alternative array list for the get_collider() function.

For example:

var enemies = get_node("../Enemies").get_meta_list()

print(get_collider())

for i in enemies:
	if (get_collider() == enemies[i]):
		#insert Damage Code here
		pass
	pass

or…

var enemies = get_node("../Enemies").get_children()

print(get_collider())

for i in enemies:
	if (get_collider() == enemies[i]):
		#insert Damage Code here
		pass
	pass

Would any of this work so then upon collision it can damage the player?

:bust_in_silhouette: Reply From: umfk

From what you said and from your examples I don’t see any reason for you to use an array for this. You probably created an “Enemy” scene which you are instancing for every enemy, correct? Then simply let that scene check for a collision between itself and the player. One enemy does not need to know about the others for this to work, every enemy checks only itself. You can do that by simply using is_colliding() inside of the _fixed_process function of the enemy script.

Let me make another remark: for loops in Python and by extension in GDScript work differently than in many other languages. Instead of

for i in enemies:
    ...enemies[i]...

you should use

for enemy in enemies:
    ...enemy...`

Thanks for the info! This helped me out with getting the player object to detect a specific enemy upon collision. Here is the refined code:

for enemy in enemies:
#print (i)
if (get_collider() == enemy):
print(“Ouch!”)

Thanks for the help!

Corruptinator | 2016-02-24 03:48

If an answer is helpful you can use the buttons on the left to upvote it so others can find it more easily. If you get a bunch of answers you can also select the “best” one that answered your question.

umfk | 2016-02-24 14:03