GunPart.gd (Base Script for all attachable parts)
- This script will be inherited by specific parts (like
Barrel.gd, Scope.gd).
- It defines the interface for how a part interacts with the
GunBase.
# res://Guns/Parts/GunPart.gd
class_name GunPart
extends Node3D
# Stats this part modifies (e.g., {"damage_modifier": 5, "accuracy_boost": 0.1})
export var stat_modifiers: Dictionary = {}
# Type of part (e.g., "Barrel", "Scope", "Magazine"). Used for slot compatibility.
export var part_type: String = "Generic"
# Reference to the gun base this part is attached to
var gun_owner: Node # Will be GunBase
# Called when the part is attached to a gun
func _on_attach(owner: Node) -> void:
gun_owner = owner
# print(name, " attached to ", gun_owner.name)
# Example: A scope might connect to the gun's "aiming" signal here
pass
# Called when the part is detached from a gun
func _on_detach() -> void:
# Example: A scope might disconnect signals here
# print(name, " detached from ", gun_owner.name)
gun_owner = null
pass
# Optionally, parts can have their own visuals.
# This function helps hide/show them based on whether they are equipped on a gun
# or just sitting in an inventory.
func set_visuals_active(active: bool):
for child in get_children():
if child is GeometryInstance3D: # MeshInstance3D, etc.
child.visible = active
elif child is Node3D: # Recurse for nested visuals
# A bit simplistic, might need more robust logic for complex parts
if "set_visuals_active" in child:
child.set_visuals_active(active)
GunBase.gd (The main gun script)
- This script will be on the root node of your
GunBase.tscn.
# res://Guns/Base/GunBase.gd
class_name GunBase
extends Node3D
signal shot_fired(projectile_spawn_transform)
signal ammo_changed(current_clip, current_reserve)
signal reloaded
signal stats_recalculated
# --- EXPORTS ---
export var base_stats_resource: GunStats
export var auto_equip_parts_on_ready: bool = true # For testing: automatically equip child parts
# --- NODES ---
# These should be Node3D children of GunBase, marking specific locations
onready var muzzle_point: Node3D = $MuzzlePoint
onready var animation_player: AnimationPlayer = $AnimationPlayer # Optional, for fire/reload anims
# Attachment slots. These are Node3D children whose names define the slot.
# e.g., $AttachmentSlots/BarrelSlot, $AttachmentSlots/ScopeSlot
onready var attachment_slots_node: Node = $AttachmentSlots
# --- STATS ---
# These are the *effective* stats after part modifiers
var current_stats: Dictionary = {}
var current_ammo_clip: int = 0
var current_reserve_ammo: int = 0
# --- STATE ---
var can_shoot: bool = true
var is_reloading: bool = false
var attached_parts: Dictionary = {} # slot_name -> GunPart instance
# --- TIMERS ---
var fire_rate_timer: Timer
var reload_timer: Timer
func _ready() -> void:
if not base_stats_resource:
printerr("GunBase: No base_stats_resource assigned!")
return
# Initialize timers
fire_rate_timer = Timer.new()
fire_rate_timer.one_shot = true
fire_rate_timer.connect("timeout", self, "_on_fire_rate_timer_timeout")
add_child(fire_rate_timer)
reload_timer = Timer.new()
reload_timer.one_shot = true
reload_timer.connect("timeout", self, "_on_reload_timer_timeout")
add_child(reload_timer)
# Initialize from base stats
_initialize_from_base_stats()
_recalculate_effective_stats() # Initial calculation
if auto_equip_parts_on_ready:
_auto_equip_child_parts()
emit_signal("ammo_changed", current_ammo_clip, current_reserve_ammo)
func _initialize_from_base_stats():
# Copy base stats to current_stats dictionary for modification
current_stats.damage = base_stats_resource.damage
current_stats.fire_rate = base_stats_resource.fire_rate
current_stats.projectile_speed = base_stats_resource.projectile_speed
current_stats.projectile_scene = base_stats_resource.projectile_scene
current_stats.max_ammo_clip = base_stats_resource.max_ammo_clip
current_stats.total_ammo_capacity = base_stats_resource.total_ammo_capacity
current_stats.reload_time = base_stats_resource.reload_time
current_stats.spread_angle = base_stats_resource.spread_angle
current_stats.recoil_amount = base_stats_resource.recoil_amount
# ... and any other stats
current_ammo_clip = current_stats.max_ammo_clip
current_reserve_ammo = current_stats.total_ammo_capacity
func _recalculate_effective_stats() -> void:
# Reset to base stats before applying part modifiers
_initialize_from_base_stats()
for part_instance in attached_parts.values():
if part_instance and part_instance.stat_modifiers:
for stat_name in part_instance.stat_modifiers:
if current_stats.has(stat_name):
# Simple additive modification. You might want multiplicative, etc.
var modifier = part_instance.stat_modifiers[stat_name]
current_stats[stat_name] = current_stats[stat_name] + modifier
else:
# Part trying to modify a non-existent stat (or new stat)
current_stats[stat_name] = part_instance.stat_modifiers[stat_name]
# Ensure clip size isn't negative etc.
current_stats.max_ammo_clip = max(1, int(current_stats.max_ammo_clip))
current_stats.fire_rate = max(0.1, float(current_stats.fire_rate)) # Avoid division by zero
# If clip size changed, adjust current ammo
current_ammo_clip = min(current_ammo_clip, int(current_stats.max_ammo_clip))
# print("Recalculated Stats: ", current_stats)
emit_signal("stats_recalculated")
emit_signal("ammo_changed", current_ammo_clip, current_reserve_ammo)
func _auto_equip_child_parts():
# For easy testing: parts that are children of slots in the editor get equipped
if attachment_slots_node:
for slot_node in attachment_slots_node.get_children():
if slot_node.get_child_count() > 0:
var part_candidate = slot_node.get_child(0)
if part_candidate is GunPart:
# Detach from current parent (the slot) and re-attach properly
slot_node.remove_child(part_candidate)
attach_part(part_candidate, slot_node.name)
else:
printerr("GunBase: Child ", part_candidate.name, " in slot ", slot_node.name, " is not a GunPart.")
# --- PUBLIC API ---
func can_fire() -> bool:
return can_shoot and not is_reloading and current_ammo_clip > 0
func attempt_shoot() -> void:
if can_fire():
_shoot()
func attempt_reload() -> void:
if not is_reloading and current_ammo_clip < int(current_stats.max_ammo_clip) and current_reserve_ammo > 0:
_reload()
# --- CORE LOGIC ---
func _shoot() -> void:
if not base_stats_resource.projectile_scene:
printerr("GunBase: No projectile_scene defined in GunStats!")
return
if not muzzle_point:
printerr("GunBase: MuzzlePoint node not found!")
return
current_ammo_clip -= 1
can_shoot = false
fire_rate_timer.start(1.0 / float(current_stats.fire_rate))
# Instantiate projectile (implement Projectile.tscn later)
var projectile_instance = base_stats_resource.projectile_scene.instance()
# It's good practice for the game world or a projectile manager to parent projectiles
# get_tree().current_scene.add_child(projectile_instance) # Example
# For now, let's just emit a signal with spawn info
# The player or a weapon controller can listen to this and spawn it.
emit_signal("shot_fired", muzzle_point.global_transform, projectile_instance, current_stats)
# Optional: Play animation
if animation_player and animation_player.has_animation("fire"):
animation_player.play("fire")
# print("BANG! Ammo: ", current_ammo_clip, "/", current_reserve_ammo)
emit_signal("ammo_changed", current_ammo_clip, current_reserve_ammo)
func _reload() -> void:
is_reloading = true
# print("Reloading...")
# Optional: Play animation
if animation_player and animation_player.has_animation("reload"):
animation_player.play("reload")
# If animation duration matches reload_time, you can use its finish signal
# For simplicity, we'll use a timer.
reload_timer.start(float(current_stats.reload_time))
else:
reload_timer.start(float(current_stats.reload_time)) # Start timer if no anim
func _on_fire_rate_timer_timeout() -> void:
can_shoot = true
func _on_reload_timer_timeout() -> void:
is_reloading = false
var ammo_needed = int(current_stats.max_ammo_clip) - current_ammo_clip
var ammo_to_transfer = min(ammo_needed, current_reserve_ammo)
current_ammo_clip += ammo_to_transfer
current_reserve_ammo -= ammo_to_transfer
# print("Reloaded! Ammo: ", current_ammo_clip, "/", current_reserve_ammo)
emit_signal("reloaded")
emit_signal("ammo_changed", current_ammo_clip, current_reserve_ammo)
# --- ATTACHMENT LOGIC ---
func attach_part(part_instance: GunPart, slot_name: String) -> bool:
var slot_node = attachment_slots_node.get_node_or_null(slot_name)
if not slot_node:
printerr("GunBase: Attachment slot '", slot_name, "' not found.")
return false
# Optional: Check part_type compatibility with slot if you implement that
# e.g., if slot_node has an `export var compatible_part_types: Array[String]`
# Detach existing part if any
if attached_parts.has(slot_name):
detach_part(slot_name)
# Parent the part's visual node to the slot
slot_node.add_child(part_instance)
part_instance.owner = self # Important for scene saving if parts are instanced at runtime
# Store reference and notify part
attached_parts[slot_name] = part_instance
part_instance._on_attach(self)
part_instance.set_visuals_active(true) # Make sure visuals are on
_recalculate_effective_stats()
return true
func detach_part(slot_name: String) -> GunPart:
if attached_parts.has(slot_name):
var part_instance = attached_parts[slot_name]
part_instance._on_detach()
part_instance.set_visuals_active(false) # Hide visuals or prepare for inventory
if part_instance.get_parent(): # Should be the slot_node
part_instance.get_parent().remove_child(part_instance)
attached_parts.erase(slot_name)
_recalculate_effective_stats()
return part_instance # Return it so it can be added to inventory, dropped, etc.
return null
func get_attached_part_in_slot(slot_name: String) -> GunPart:
return attached_parts.get(slot_name, null)
# --- UTILITY ---
func add_ammo(amount: int):
current_reserve_ammo = min(current_reserve_ammo + amount, int(current_stats.total_ammo_capacity))
emit_signal("ammo_changed", current_ammo_clip, current_reserve_ammo)
Projectile.tscn and Projectile.gd (Basic Projectile)
- This is what the gun fires.
# res://Guns/Projectiles/Projectile.gd
class_name Projectile
extends Area3D # Or RigidBody3D if you want physics-based bullets
var speed: float = 100.0
var damage: float = 10.0
var lifetime: float = 3.0 # Seconds before self-destructing
func _ready() -> void:
# Connect to body_entered for collision detection (if Area3D)
connect("body_entered", self, "_on_Projectile_body_entered")
# Self-destruct timer
var timer = Timer.new()
timer.wait_time = lifetime
timer.one_shot = true
timer.connect("timeout", self, "queue_free")
add_child(timer)
timer.start()
func _physics_process(delta: float) -> void:
# Move forward
global_translate(transform.basis.z * speed * delta)
func _on_Projectile_body_entered(body: Node) -> void:
# print("Projectile hit: ", body.name)
if body.has_method("take_damage"): # Check if the body can take damage
body.take_damage(damage, global_transform.origin, transform.basis.z) # Origin and direction
# For simplicity, destroy on any hit. You might want penetration, ricochets etc.
queue_free()
# Call this after instancing to set its properties from the gun
func initialize(p_transform: Transform, p_damage: float, p_speed: float):
global_transform = p_transform
damage = p_damage
speed = p_speed
- Projectile.tscn Scene Structure:
Projectile (Area3D) (with Projectile.gd script)
CollisionShape3D (e.g., a small SphereShape3D or CapsuleShape3D)
MeshInstance3D (e.g., a small sphere or capsule mesh for visibility)
(Optional) OmniLight3D (for tracer effect)
(Optional) GPUParticles3D (for trail effect)