0 votes

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.

asked Jan 15 in Engine by JhimBhoy (12 points)
edited 6 days ago by JhimBhoy

1 Answer

+1 vote

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()

answered Jan 15 by Roket (47 points)

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 :)

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()
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.