When working with CollisionObject2D, such as physics bodies or Area2D, I often find myself wanting to check if a point (as Vector2) is touching a CollisionObject.

After looking around online, I couldn't find any clean/easy way to do it besides something like this:

  1. Get all CollisionShape2D of an object
  2. iterate through each CollisionShape2D, find the Shape assigned to it.
  3. match the shape found to circle or polygon (not sure if Geometry can handle capsules, partially obscured raycasts may need manual calculations later)
  4. use Geometry to check is a given point is inside the shape, accounting for relative positions, rotations etc.
  5. return true if any CollisionShape2D's Shape' is colliding with the point

Alternatively:

  1. create a scene that is an Area2D with a CollisionShape2D that is a tiny circle.
  2. when collision with point needs to be checked, instance that scene, place it in the right location, give it the right collision layers
  3. update new Area2D to find intersecting bodies/shapes and see if it is colliding with the tested object

Both methods seem to have notable problems (second one is borderline unhinged, I know). I feel like there really should be a better way to do this, some function built into CollisionObject2D perhaps, and with access to lower level code, checking collision with a single point must be easier than any methods similar to the ones I outlined.

  • xyz replied to this.
  • GE100 You can use PhysicsDirectSpaceState2D::intersect_point()

    var = PhysicsPointQueryParameters2D.new()
    pp.collide_with_areas = true 
    pp.position = get_global_mouse_position()
    if get_world_2d().direct_space_state.intersect_point(pp, 1):
    	print("HIT")

    Look at the reference for PhysicsPointQueryParameters2D that is passed as input to intersect_point() to see all the details on how the query can be customized.

    GE100 You can use PhysicsDirectSpaceState2D::intersect_point()

    var = PhysicsPointQueryParameters2D.new()
    pp.collide_with_areas = true 
    pp.position = get_global_mouse_position()
    if get_world_2d().direct_space_state.intersect_point(pp, 1):
    	print("HIT")

    Look at the reference for PhysicsPointQueryParameters2D that is passed as input to intersect_point() to see all the details on how the query can be customized.