0 votes

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 collidewithbodies 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()
Godot version v3.4.3.stable.official [242c05d12]
in Engine by (296 points)

1 Answer

0 votes
Best answer

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()
by (296 points)
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.