0 votes

I've a Raycast2d to check collisions and and I need to get the object that it has collided with to know the size and position of its collisionshape, but raycast.is_colliding() only gets the object (node), and if I don't know the collisionShape node name i can't get it.

The Scene:

Player (KinematicBody2D)

Stone (RigidBody2D)
   CollisionShape2D (CollisionShape2D)

AnotherObstacle (Area2D)
   CollisionShape2D (CollisionShape2D)


if Player.RayCastTop.IsColliding():
    var collisionShape2d = getCollisionShape2D (Player.RayCastTop.GetCollider())
    collisionShape.Height = ??
    collisionShape.Width = ??

If there any way to get the CollisionShape2D of an object returned by raycast.get_collider() ?

in Engine by (52 points)

1 Answer

+1 vote
Best answer

Nothing special about it. Assuming the CollisionShape2D is a direct child of the node the Raycast2D is colliding with, it would be as simple as this:

var collider = raycast.get_collider()
if collider:
    var collision_shape = collider.get_node("CollisionShape2D")
    # ...

If it's not a direct child, than you need to adapt the NodePath accordingly.

by (10,421 points)
selected by

What if the ennemy has for example a head and a body : how can I know if the bullet reaches the head or the body ?

If both head and body have their own body, it works exactly the same. If they don't (i.e. the enemy is one body with two collision shapes belonging to it), you can do:

var collider = raycast.get_collider()
if collider:
    var i = raycast.get_collider_shape()
    var hit_node = collider.shape_owner_get_owner(i)

OMG thank you ! I didn't know you could get multiple colliders like that !!!

Very helpful, but let me add that this only works with GodotPhysics and not with Bullet because getcollidershape() is currently broken with Bullet.

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.
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 webmaster@godotengine.org with your username.