'Spawning rigidbodies with velocity

So I am making a gun in a Godot game. I want to use rigidbodies for the bullets, and it spawns like normal out of the gun. However, I cannot seem to find a way to spawn the rigidbody bullets, with velocity. Here is my code so far, I would love some help with this! (I am using gdscript, and I am new to Godot):

extends Position3D

signal spawned(spawn)

export(PackedScene) var spawnling_scene

func _physics_process(delta):
    if Input.is_action_pressed("leftClick"):
        spawn()

func spawn():
    var spawnling = spawnling_scene.instance()

    add_child(spawnling)
    spawnling.set_as_toplevel(true)


    emit_signal("spawned", spawnling)
    return spawnling


Solution 1:[1]

You can write the linear_velocity of the RigidBody3D before you add it to the scene tree. Here is a quick example:

extends Position3D


func _input(event: InputEvent) -> void:
    var bullet := preload("res://scenes/bullet/bullet.tscn")
    if event.is_action_pressed("ui_accept"):
        var bullet_instance := bullet.instance() as RigidBody
        bullet_instance.linear_velocity = Vector3.RIGHT * 50
        add_child(bullet_instance)
        bullet_instance.set_as_toplevel(true)

how do I make it so that instead of going in one direction, it goes in the direction that I face?

The Basis of the transform has the direction of the axis. Since we usually use the z axis as forward direction in Godot, usually the z axis of the Basis is the direction it is facing:

bullet_instance.linear_velocity = global_transform.basis.z * 50

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1