[SOLVED] When two RigidBody2D objects collide I want to destroy one of them

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

I have circular RigidBody2D objects in separate nodes. Think of them as pool balls.

When two of these objects collide I want to destroy only one.

I’ve tried this

func _on_RigidBody2D_body_entered(body):
var nameOfCollider = body.get_parent().get_name()
if (nameOfCollider.substr(0,4) == "ball"):
	print ("hit " + nameOfCollider)
	queue_free()
	var rigidBody = get_node("RigidBody2D")
	rigidBody.set_physics_process(false)
	rigidBody.set_process(false)

in the root of the node.

But this destroys both of them.

What can I do to make only one be destroyed?

Thanks in advance.

:bust_in_silhouette: Reply From: Roket

As an option, you can give an id to each RigidBody2D and delete only the one that has this id less.

Also, instead of id, I think you can use get_path () and also delete only the object whose path is less.

if get_path() < body.get_path():
    queue_free()
else:
    body.queue_free()

But in this case you need to check object is deleted or not with is_instance_valid()

Thanks for the reply.

That’s a good idea but the problem I have is their order or index doesn’t matter.
I’ll have a look at is_instance_valid()

Thanks again :slight_smile:

JhimBhoy | 2020-01-15 18:28

Here is what I did to solve this.

Each node is named using the convention ball<number> and when two nodes collide I add the number of the current ball to the colliding balls collision array. I then iterate over this array and check if the node has been previously collided with.

var collisions = []

func _on_RigidBody2D_body_entered(body):
	var ownNumber = self.get_name().substr(4,3)
	var collider = body.get_parent()
	var nameOfCollider = collider.get_name()
	var numberOfCollider = collider.get_name().substr(4,3)
	
	if (nameOfCollider.substr(0,4) == "ball"):
		var alreadyCollided = false
		for i in collisions:
			if i == numberOfCollider:
				alreadyCollided = true
			
		if (!alreadyCollided):
			print ("hit " + nameOfCollider )
			collider.collisions.push_back(ownNumber)
			queue_free()

JhimBhoy | 2020-01-18 15:05