Sphere Trace Or Capsule Overlap In Godot

Sphere Trace Or Capsule Overlap In Godot

If you want to detect all overlapping bodies of a sphere moving along a line segment in Godot, you can use intersect_shape with a capsule oriented along the sphere's path.

Here's an example function you can use to do this in GDScript:

func get_overlapping_colliders_in_capsule(
    start_position: Vector3,
    end_position: Vector3,
    radius: float = 0.2,
    collision_mask: int = 4294967295,
    max_results: int = 32) -> Array[Dictionary]:

    var space := get_world_3d().direct_space_state

    var query := PhysicsShapeQueryParameters3D.new()
    query.collision_mask = collision_mask
    query.collide_with_bodies = true    

    var distance := (end_position - start_position).length()

    # Setup the query shape as a capsule where one tip touches start_position
    # and the other tip touches the end_position.
    var capsule := CapsuleShape3D.new()
    var capsule_shape := CapsuleShape3D.new()
    capsule_shape.height = distance
    capsule_shape.radius = radius

    query.shape = capsule_shape    
    query.transform.origin = start_position
    query.transform = query.transform.looking_at(end_position) \
        .translated_local(Vector3.FORWARD * (distance / 2.0)) \
        .rotated_local(Vector3.RIGHT, PI / 2.0)

    var results := space.intersect_shape(query, max_results)
    return results

If you want to get the active camera position, you can do the following:

var viewport := get_viewport()
var camera := viewport.get_camera_3d()
var camera_position := camera.global_position