How to work with get_colliding_bodies() ?

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

Hey everyone, I’m having trouble understanding how to work with the return data of get_colliding_bodies(). What kind of data type is being returned and how can I check if a node in the coliBodies array matches a node I want to run some code on?

extends RigidBody2D

func _ready():
	set_contact_monitor(true)
	set_fixed_process(true)
	pass
	
func _fixed_process(delta):
	var coliBodies = get_colliding_bodies()
	if coliBodies.size() > 0:
		print(coliBodies)
	pass

Output:

[[KinematicBody2D:585]]
[[StaticBody2D:583]]
[[KinematicBody2D:585]]
[[KinematicBody2D:585]]

Part 2: For Loop Problems
I cannot get the array returned by get_colliding_bodies() to loop through a simple for loop. I always receive: Invalid get index ‘[StaticBody2D:583]’ (on base: ‘Array’).

I answered my own original question:

extends RigidBody2D

func _ready():
	set_contact_monitor(true)
	set_fixed_process(true)
	pass
	
func _fixed_process(delta):
	var coliBodies = get_colliding_bodies()
	#coliBodies will always have an empty index of 0, the 0 index is assinged to the first colliding body, then adds another empty index.
	#so we check if the size is > 0
	#empty may not be proper term
	if coliBodies.size() > 0:
			print(coliBodies[0])
			print(coliBodies.size())
			if get_node("../paddle") == coliBodies[0]:
				print("Ball paddle contact.")
	pass

201Dev | 2016-08-12 12:15

:bust_in_silhouette: Reply From: Adam Zahran

Welcome to Godot Q&A :slight_smile:

What kind of data type is being returned?

That kind of data types:

[[KinematicBody2D:585]]
[[StaticBody2D:583]]

You can always check the classes documentation at the top right section of the code editor to see what kind of functions and operations you can perform on the returned body.

How can I check if a node in the coliBodies array matches a node I want to run some code on?

To check if a given instance inherits from a given class the extends keyword can be used as an operator. For example:

# use 'extends' to check inheritance
if (entity extends KinematicBody2D):
    entity.apply_damage()

You can read more about the available operators and language features here.