Do raycasts take time to calculate? --Help with a hitscan weapon

Godot Version

4.4

I’ve created a shotgun blast that involves a dozen short raycasts so that enemies can get hit by partial shots, corners can half-block, etc. Each of the raycasts instantiates a line2d for the visual aspect of the shot, (I thought about using collidable GPU particles for this, but just haven’t been able to get them working right) which draws from the shot’s origin point out to either the collision point of the hitscan or a node that marks its target point, if the shot misses.

The raycasts work perfectly and never miss, from what I can tell. But the line2ds tend to draw their full length a few frames ahead of the raycast marking the collision, and then reverting back to their collision point target instead.

2025-05-09 14-43-40

Do raycasts take a few frames to calculate? And if so, how do I work around that? Also happy to hear better methods, this was just the best I could come up with.

Here is the code that governs the raycasts and the generates the lines:

	for raycast in hurtbox_raycasts.get_children():	
		var endpoint: Vector2
		var ray_hit_assigned = false
		if (raycast.is_colliding() == true) and (ray_hit_assigned == false):
			ray_hit_assigned = true
			endpoint = raycast.get_collision_point()
		elif (raycast.is_colliding() == false) and (ray_hit_assigned == false):
			ray_hit_assigned = true
			endpoint = raycast.get_child(0).global_position
		else: print
		var pellet = PELLET.instantiate()
		get_parent().add_child(pellet)
		var starting_position = position
		pellet.start_point = starting_position
		pellet.end_point = endpoint
		

GPU particles have their own (simpler) collision system and won’t report collisions back. You can’t use them for this.

RayCast2D only updates collision information every physics frame so, if you are doing that piece of code inside a _process() function it won’t work correctly. Do it inside a _physics_process() function.

If that’s not possible or it doesn’t work then you can force an update in the raycast with RayCast2D.force_raycast_update()

Thanks! It was already in the physics process, but forcing the raycast update at the beginning of the loop fixed it.

Out of curiosity: I was only hoping to use GPU particles for the visual, and keep the hitscan raycasts as the actual method to deliver attacks. Is there any reason to not use GPU particles in that case? I’ve stuck to CPU particles entirely, because they’ve been a lot easier to get going.

Ah, okay. Yeah, for visuals it should work fine.