Using intersect_ray to query for a single body

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

Hello. I am working on script for a 2d horror game heavily inspired by Clock Tower and all movement is right and left, single axis. I have a monster who chases the player. My goal with this:

  • The monster should query the space to see if the player is there.
  • If not, they change direction.
  • There are only 2 kinematic bodies, so collide_with_bodies is what I need.

Seems simple enough but my implementation is not working. I know it’s how I am coding it because the debug message I scripted is not even printing, my movement is working and no errors popping up. Collision layers, masks and z-index are the same for all objects involved. Can’t find out why it’s not working.

func line_of_sight():
var vision = get_world_2d().direct_space_state
var field = get_viewport().size
var spotting_right = vision.intersect_ray(self.global_position, Vector2(field.x,0), [self])
var spotting_left = vision.intersect_ray(self.global_position, Vector2(0,0), [self])

if "collide_with_bodies" in spotting_right:
	print("Spotted!")
	walk_right()
if "collide_with_bodies" in spotting_left:
	print("Spotted!")
	walk_left()
:bust_in_silhouette: Reply From: SnapCracklins

I figured it out. One of my objects was in a wrong collision mask. Hence why no data was returning.
If anyone needs it, I will plug this in here.

func line_of_sight():
### get world space, port size, exclude others objects, x and y limits
var vision = get_world_2d().direct_space_state
var field = get_viewport().size
var exclude = [self, Area2D, StaticBody2D, RigidBody2D]
var head = self.global_position.y
var feet = self.global_position.x

### check for ray intersect in both directions
### first argument origin, second arg terminus, third is array for ignore
var spotting_right = vision.intersect_ray(Vector2(feet,head), Vector2(field.x,head), exclude)
var spotting_left = vision.intersect_ray(Vector2(feet,head), Vector2(0,head), exclude)

### add a gap to turning and change movement if ray intersects
yield(get_tree().create_timer(turnGap),"timeout")
if spotting_right:
	print("Spotted!")
	walk_right()
if spotting_left:
	print("Spotted!")
	walk_left()