Help me understand Physics2DDirectSpaceState.intersect_point

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Schazzwozzer

Hello! I’m starting to tinker with Godot’s geometry capabilities, and I’ve immediately run into a problem: I can’t get intersect_point to work.

I’ve got a very simple scene: an Area2D with a corresponding CollisionShape2D. A Sprite so that I can visualize the area. Another Sprite which I can move around (using a simple control script), and which serves as the “point” against which I am testing for intersection.

The script is similarly simple and pretty closely inspired by this raycast guide. This function is executed from _physics_process:

func check_intersection( position : Vector2 ):
var intersections = get_world_2d().direct_space_state.intersect_point( position )

for i in intersections:
	print( "Intersection: " + intersections[i] );

The “position” Vector2 parameter is the global_position of my “Position Test” node.

So, when I move the “Position Test” node into the Area2D, I would expect it to print something to the console… but nothing happens. I feel like I’m missing something obvious or I’ve made some small mistake. Help!

:bust_in_silhouette: Reply From: Schazzwozzer

I’ve solved this issue. It turns out that, by default, intersect_point collides with bodies, but not areas. In order to detect areas, you have to pass it several optional parameters.

var intersections = get_world_2d().direct_space_state.intersect_point( 
	position, 32, [], 0x7FFFFFFF, true, true )

Everything except the first and last parameters are just the default values, as shown in the documentation.

Oh, and because evaluating the results felt a bit esoteric to me, here is how I did that.

for i in range( intersections.size() ):
	if intersections[i].collider == self.get_parent():

In this case, collideris the intersecting Area2D.

My Vector2 still doesn’t collide with areas, even when set to true. I used this exact code with the position squarely within the area.

Edit: My problem was that my areas were inside of a CanvasLayer. For some reason you have to use intersect_point_on_canvas() as seen in the documentation

wetbadger | 2021-09-05 03:02