Godot Engine – Raycast shotgun tutorial

This article is also available on Odysee.

This quick tutorial shows you how to use multiple raycasts in the same physics frame in the Godot Engine. This is useful for raycast (also called hitscan) weapons like shotguns that fire multiple pellets at the same time.

Here’s the problem: by default, this doesn’t work in Godot and only the last of multiple raycast is taken into account if they are fired in the same physics frame. So no matter how many pellets you want to fire, you always end up with just one.

The solution to this problem is the force_raycast_update() function.

Let’s take a look at some example code, where we put a script on a Spatial Node with a RayCast node as a child.

# Random spread in degrees
var random_spread = 3
# Number of projectiles per shot
var number_of_pellets = 8

func shoot():
    # Run this code for each pellet
    for i in range(number_of_pellets)
        # Calculate random pitch and yaw, roll is always 0
        var random_spread = Vector3(rand_range(-spread, spread), rand_range(-spread, spread), 0)
        # Rotate the raycast node
        $RayCast.rotation_degrees = random_spread
        # Save the impact position
        var impact_position = $RayCast.get_collision_point()
        # The important part: update the raycast immediately
        $RayCast.force_raycast_update()

This function calculates a random rotation for the pitch and yaw (roll is always 0) and then rotates the RayCast node accordingly. However, no matter how many pellets you want to shoot in your for loop, you always end up with only one ray. As soon as you add the last line, $RayCast.force_raycast_update(), multiple raycasts will work.

force_raycast_update() forces a raycast update, even if multiple rays from the same source are fired in the same physics frame. You can take a look at the official documentation for more info.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Nach oben scrollen