How to get the node that collided with a CollisionPolygon2D in an Area2D

Godot Version

4.2.2

Question

Hi Folks,

I’m making a little Asteroids clone to try my hand at game development. When the player’s projectiles hit an asteroid, I’d like the asteroid’s “children” to get some of the projectile’s momentum. To do this, I’d like to add a part to the asteroid’s _on_area_entered method that picks up the projectile’s velocity. Is there any way to do this? Thanks for any and all help.

Do you have a node setup for this already? It’s hard to suggest code without it.

Are your projectiles rigidbodies? Do they have an extra hitbox area or just use the rigidbody collision? And what about the asteroid’s children? Are they also rigidbodies that get activated once broken up? And are we talking 2D or 3D?

Your code would look a little something like this but the details are gonna depend on your node setup so it might not work exactly as below. If you have one already, a screenshot of the scene tree would help. :>

@export var momentum: float = 0.5
@export var children: Array[Rigidbody] # Either Rigidbody2D or 3D

# Freeze all children rigidbodies so they don't fly around
func _ready():
	for c in children:
		c.freeze = true

func _on_area_body_entered(body):
	if body is Projectile:
		for c in children:
			c.freeze = false # Activates children rigidbodies
			c.velocity = body.velocity * momentum # Applies fraction of projectile momentum

Hi Redkite,

Right now, my projectiles area Area2Ds (maybe I should learn more ways to make entities…) Here are the scene trees for projectiles and asteroids.
8-31-24-1
8-31-24-2

Oh, I figured it out - the area parameter of _on_area_entered has what I need. Thank you!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.