Godot Version
4.6.1
Question
I’m working on an FPS game, one where the bullets are physical objects (RigidBody3D). I have weapons be added to the playercharacter node when the player acquires them, however I have ran into some issues.
The bullets that I fire always spawn at (0,0,0), even with the player moving around and rotating. The bullets do fire at the right angle however. I’m honestly not sure what is going on, since everything should be working fine, so there might be a problem outside of the scripts themselves.
I will say that the weapon did work fine when I originally had the pistol node be a child of the playercharacter in the editor. I removed it and instead used “add_child()” since I wanted to add/remove it when the player picked it up, and only then did the problems start.
The script for adding the pistol is:
if global.haspistol == true:
var pistolpath = preload("res://scenes/weapons/pistol.tscn").instantiate()
add_child(pistolpath)
The pistol itself:
extends Node3D
@onready var gunbarrelraycast = $RayCast3D
func _ready():
get_parent().connect("use", _use)
func _use():
var instance = preload("res://scenes/weapons/projectiles/bullet.tscn").instantiate()
instance.position = $RayCast3D.target_position
instance.transform.basis = gunbarrelraycast.global_transform.basis
get_parent().add_child(instance)
func _process(delta):
pass
And the bullet:
extends RigidBody3D
const BULLETSPEED = 400.0
@onready var mesh = $MeshInstance3D
func _ready():
# move where the player fired it from
request_ready()
linear_velocity = Vector3(0,0,0)
apply_central_force(self.transform.basis * Vector3( 0, 0, - BULLETSPEED))
# don't want missed bullets to lag up the game, so despawn after a while
await get_tree().create_timer(10).timeout
queue_free()
func impact():
# create flashbang effect
var instance = preload("res://scenes/weapons/vfx/pistolflashbang.tscn").instantiate()
instance.position = self.global_position
get_parent().add_child(instance)
queue_free()
func _physics_process(delta):
# if hit something, despawn
if self.get_colliding_bodies():
print(str(get_colliding_bodies()))
impact()