Hello. I'm making a grid-based click-to-move game where I use the A* algorithm to create paths for the characters to follow, except, instead of having the characters follow the paths exactly, I am trying to simplify the paths by cast a ray from waypoints, starting with the grid cell that a character is standing on, to each other cell in the path. This is so that, if there are no obstacles in the character's way, the character can just run diagonally to the target cell, instead of zig-zagging to it, and if there are obstacles in the way, then, every time the ray hits an obstacle, a waypoint gets added to a list and becomes the new origin for the ray. Once the ray is cast to the last cell in the path, the character would follow the waypoints instead of the path, but still avoid obstacles. For some reason, though, the ray is not hitting anything. I have the RayCast3D node enabled and on collision mask 2, the obstacles' static bodies on layer 2 and collision mask 2, exclude parent is on, and collide with bodies is on, I also enable the RayCast3D in my line-of-sight-checking function, which looks like this:
func LineOfSightCheck():
ray.enabled = true
var rayOrigin = startCell
for i in len(path):
ray.global_position = rayOrigin["location"]
ray.target_position = path[i]["location"]
print("origin: ", ray.global_position)
print("target position: ", ray.target_position)
if ray.is_colliding():
print("Hit.")
waypoints.append(path[i - 1])
rayOrigin = path[i - 1]
if i == len(path) - 1:
waypoints.append(destination)
I confirmed that the ray is getting cast from the origin to the grid cells that make up the path, but the ray never hits anything. I also extended the obstacles' colliders slightly under the ground so that the ray doesn't just go right under them and miss them. Does anyone know why the ray isn't hitting anything?
RayCast3D isn't colliding with anything
- Edited
- Best Answerset by Rygell
Rygell You can't just reposition the raycast node in a loop and query if it's colliding like that. It takes a physics tick for node to update. You at least need to await get_tree().physics_frame
every step of the loop for each new position to be updated/tested by the physics engine. This obviously may not be ideal if you need the results immediately so better to test hits via PhysicsDirectSpaceState3D::intersect_ray()