Changing ray position

Godot Version

4.3

Question

Hi I’m making a 2D platformer game and I’m trying to make an enemy that uses a ray to detect when it is going to go off a ledge is there a way to change the position of the origin of a ray cast depending on the direction the enemy is heading?

If you are using a RayCast2D node then changing it’s position will change the origin of the ray.

Does that work on moving bodies? Also could you give me an example in code?

If the RayCast is a child of the moving body then it will move with it’s parent.

$RayCast2D.position = Vector2(40, 0)

Maybe it would be more helpful if you showed how you set up your enemy, and how you have the enemy turn in code too.

Yes please!

I was asking for two pieces of information from you, please post:


You will get a warning for line 40, two equals signs == is for comparison. The code says to compare DownRay’s position.x to itself times direction.x, then throw away the results. You also create down_ray_pos but it’s not really used so line 39 can be deleted, and you do not need to force a raycast update.

You probably want to multiply it’s position.x by -1 like you do with current_direction

$VisionArea/DownRay.position.x *= -1

Are you doing anything with this raycast? They do not operate on their own, what do you want this raycast to be used for?

Make sure to paste code instead of screenshots

I want the ray to detect weather or not the enemy is about to walk into a pit. I’m gonna figure out the code for that once I get the ray to move

Turns out that could make the ray go in the opposite direction from the enemy. But I found a solution.

var ray_offset = Vector2(-96, 128)
down_ray.position.y = position.y + ray_offset.y
if direction.x < 0:
down_ray.position.x = position.x + -96
else:
down_ray.position.x = position.x + 96

Thank you for your help! You helped shed light on my problem.

I’ve found a better solution!

var ray_offset = Vector2(-96, 128)
down_ray.position.y = position.y + ray_offset.y
down_ray.position.x = position.x - ray_offset.x * direction.x

Here’s my current node setup. Turns out my solution only works if the ray is not a parent of the character body 2D.

Thank you again!

Oh and the code controlling the ray cast is in the code controlling the character body 2D

But my solution can be retooled to work if the ray cast is a child of the charecter body 2D.

var ray_offset = Vector2(-96, 128)
down_ray.position.y = ray_offset.y
down_ray.position.x = ray_offset.x * direction.x * -1

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.