The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

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)
    var rigidBody = get_node("RigidBody2D")

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.

in Engine by (12 points)
edited by

1 Answer

+2 votes

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

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

by (54 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 )
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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.