Projectiles+

This commit is contained in:
dingo
2026-01-18 20:45:48 -05:00
parent 32fb57fa75
commit 718a8ecb3b
14 changed files with 455 additions and 19 deletions
+51 -2
View File
@@ -21,6 +21,10 @@ signal recipe_discovered(recipe: Dictionary)
signal stash_updated(stash_data: Dictionary)
signal stash_result(result: Dictionary)
signal dungeon_tiles_updated(tiles: Array)
signal projectile_spawned(projectile_data: Dictionary)
signal projectile_hit(hit_data: Dictionary)
signal projectile_expired(expired_data: Dictionary)
signal damage_number(damage_data: Dictionary)
# Use constants instead of enum to avoid type issues
const STATE_AUTH = 0
@@ -175,6 +179,14 @@ func _on_message_received(opcode: int, data: Dictionary):
_handle_stash_state(data)
OpCodes.STASH_RESULT:
_handle_stash_result(data)
OpCodes.EVENT_PROJECTILE_SPAWNED:
_handle_projectile_spawned(data)
OpCodes.EVENT_PROJECTILE_HIT:
_handle_projectile_hit(data)
OpCodes.EVENT_PROJECTILE_EXPIRED:
_handle_projectile_expired(data)
OpCodes.EVENT_DAMAGE_NUMBER:
_handle_damage_number(data)
_:
print("[GameState] Unhandled opcode: ", opcode)
@@ -398,7 +410,25 @@ func _handle_dungeon_state(data: Dictionary):
for lc in lchests:
var lcid = lc.get("id", lc.get("Id"))
loot_chests[lcid] = lc
# Parse events (damage, deaths, projectile hits/expires)
var events = data.get("events")
if events:
# Handle damage events - spawn floating damage numbers
var damage_events = events.get("damage", [])
for dmg_event in damage_events:
damage_number.emit(dmg_event)
# Handle projectile hit events - remove projectile from client
var projectile_hits = events.get("projectileHits", [])
for hit_event in projectile_hits:
projectile_hit.emit(hit_event)
# Handle projectile expired events - remove projectile from client
var proj_expired = events.get("projectileExpired", [])
for expire_event in proj_expired:
projectile_expired.emit(expire_event)
dungeon_state_updated.emit()
func _handle_inventory_state(data: Dictionary):
@@ -491,6 +521,9 @@ func send_move(dx: float, dy: float, aim_angle: float):
func send_attack(aim_angle: float):
Network.send_message(OpCodes.INPUT_ATTACK, {"AimAngle": aim_angle})
func send_fire_projectile(direction_x: float, direction_y: float):
Network.send_message(OpCodes.INPUT_FIRE_PROJECTILE, {"DirectionX": direction_x, "DirectionY": direction_y})
func send_enter_dungeon(tier: int):
Network.send_message(OpCodes.DUNGEON_ENTER, {"Tier": tier})
@@ -731,5 +764,21 @@ func _handle_tile_update(data: Dictionary):
if not found:
dungeon.visual_tiles.tiles.append(tile)
dungeon_tiles_updated.emit(tiles)
func _handle_projectile_spawned(data: Dictionary):
print("[GameState] Projectile spawned: ", data.get("id", -1))
projectile_spawned.emit(data)
func _handle_projectile_hit(data: Dictionary):
print("[GameState] Projectile hit: ", data)
projectile_hit.emit(data)
func _handle_projectile_expired(data: Dictionary):
print("[GameState] Projectile expired: ", data.get("id", -1))
projectile_expired.emit(data)
func _handle_damage_number(data: Dictionary):
# Emit damage number for floating damage text
damage_number.emit(data)
+1 -1
View File
@@ -188,7 +188,7 @@ func _handle_received_data(packet: PackedByteArray):
var message = json.data
var opcode: int = message.get("opCode", message.get("OpCode", 0))
print("[Network] OpCode Recieved: ", opcode)
# Decode payload
var payload_data = message.get("payload", message.get("Payload", null))
var decoded_data = {}
+15
View File
@@ -205,6 +205,9 @@ const INPUT_CHEST = 403
## Client -> Server: Use portal
const INPUT_PORTAL = 404
## Client -> Server: Fire projectile (bow, crossbow, throwable)
const INPUT_FIRE_PROJECTILE = 405
# ===== Escape / Portal (450-459) =====
## Client -> Server: Start escape channel (return to hub)
@@ -236,6 +239,18 @@ const EVENT_LEVELUP = 502
## Server -> Client: Loot obtained
const EVENT_LOOT = 503
## Server -> Client: Projectile spawned in dungeon
const EVENT_PROJECTILE_SPAWNED = 504
## Server -> Client: Projectile hit target (mob/player)
const EVENT_PROJECTILE_HIT = 505
## Server -> Client: Projectile expired (max range or wall collision)
const EVENT_PROJECTILE_EXPIRED = 506
## Server -> Client: Damage number for floating text
const EVENT_DAMAGE_NUMBER = 507
# ===== Server Broadcasts (600-609) =====
## Server -> All Clients: Server-wide broadcast message
+62
View File
@@ -0,0 +1,62 @@
extends Node2D
## Floating damage number that appears above entities when they take damage
var damage_amount: int = 0
var damage_color: Color = Color.RED
var lifetime: float = 2.0
var elapsed: float = 0.0
@onready var label: Label = null
func _ready():
# Create label
label = Label.new()
label.name = "Label"
label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
add_child(label)
# Set label properties
label.add_theme_font_size_override("font_size", 18)
label.add_theme_color_override("font_color", damage_color)
label.add_theme_color_override("font_shadow_color", Color.BLACK)
label.add_theme_color_override("font_outline_color", Color.BLACK)
label.add_theme_constant_override("shadow_offset_x", 2)
label.add_theme_constant_override("shadow_offset_y", 2)
label.add_theme_constant_override("outline_size", 4)
label.text = str(damage_amount)
# Start above the entity
position.y -= 20
func _process(delta):
elapsed += delta
# Float upward
position.y -= 30 * delta
# Fade out over lifetime
var alpha = 1.0 - (elapsed / lifetime)
if label:
var color_with_alpha = damage_color
color_with_alpha.a = alpha
label.add_theme_color_override("font_color", color_with_alpha)
var shadow_color = Color.BLACK
shadow_color.a = alpha
label.add_theme_color_override("font_shadow_color", shadow_color)
label.add_theme_color_override("font_outline_color", shadow_color)
# Remove when lifetime expires
if elapsed >= lifetime:
queue_free()
func initialize(dmg: int, color: Color = Color.RED):
damage_amount = dmg
damage_color = color
# Update the label if it exists
if label:
label.text = str(damage_amount)
label.add_theme_color_override("font_color", damage_color)
+1
View File
@@ -0,0 +1 @@
uid://j7nnvrpus68s
+167 -2
View File
@@ -16,6 +16,7 @@ const WORLD_TILE_SIZE := TILE_SIZE * TILE_SCALE # 32 pixels per tile in world
@onready var items_container = $Entities/DroppedItems
@onready var portals_container = $Entities/Portals
@onready var loot_chests_container = $Entities/LootChests
@onready var projectiles_container = $Entities/Projectiles
@onready var tilemap: TileMapLayer = $TileMapLayer
@onready var hud = $Hud
@onready var inventory_panel = $Inventory
@@ -31,6 +32,11 @@ var chest_scene: PackedScene = null
var item_scene: PackedScene = null
var portal_scene: PackedScene = null
var loot_chest_scene: PackedScene = null
var projectile_scene: PackedScene = null
var damage_number_scene: PackedScene = null
# Projectile tracking
var projectiles: Dictionary = {} # id -> projectile node
var aim_angle: float = 0.0
@@ -48,7 +54,11 @@ func _ready():
portal_scene = load("res://scenes/dungeon/portal.tscn")
if ResourceLoader.exists("res://scenes/dungeon/loot_chest.tscn"):
loot_chest_scene = load("res://scenes/dungeon/loot_chest.tscn")
if ResourceLoader.exists("res://scenes/dungeon/projectile.tscn"):
projectile_scene = load("res://scenes/dungeon/projectile.tscn")
if ResourceLoader.exists("res://scenes/dungeon/damage_number.tscn"):
damage_number_scene = load("res://scenes/dungeon/damage_number.tscn")
# Create visual tile renderer
visual_renderer = VisualTileMapRenderer.new()
visual_renderer.name = "VisualTileRenderer"
@@ -68,6 +78,10 @@ func _connect_gamestate():
GameState.dungeon_state_updated.connect(_on_state_updated)
GameState.state_changed.connect(_on_game_state_changed)
GameState.dungeon_tiles_updated.connect(_on_tiles_updated)
GameState.projectile_spawned.connect(_on_projectile_spawned)
GameState.projectile_hit.connect(_on_projectile_hit)
GameState.projectile_expired.connect(_on_projectile_expired)
GameState.damage_number.connect(_on_damage_number)
func _on_game_state_changed(state: String):
var is_playing = (state == "PLAYING")
@@ -202,7 +216,32 @@ func _handle_input():
# Attack on click (only if UI not open)
if not ui_open and Input.is_action_just_pressed("attack"):
GameState.send_attack(aim_angle)
# Check if player has a ranged weapon equipped
var equipped_weapon = GameState.equipment.get("weapon", null)
if equipped_weapon != null and not equipped_weapon.is_empty():
# Server sends camelCase properties
var requires_ammo = equipped_weapon.get("requiresAmmunition", false)
var is_throwable = equipped_weapon.get("isThrowable", false)
var projectile_speed = equipped_weapon.get("projectileSpeed", 0)
print("[DungeonManager] Attack - Weapon: ", equipped_weapon.get("name", "Unknown"))
print("[DungeonManager] RequiresAmmo: ", requires_ammo, ", IsThrowable: ", is_throwable, ", Speed: ", projectile_speed)
# If weapon fires projectiles (bow, crossbow, throwable), send projectile fire
if (requires_ammo or is_throwable) and projectile_speed > 0:
print("[DungeonManager] Firing projectile!")
# Calculate direction vector from aim angle
var direction_x = cos(aim_angle)
var direction_y = sin(aim_angle)
GameState.send_fire_projectile(direction_x, direction_y)
else:
print("[DungeonManager] Using melee attack")
# Melee weapon - use normal attack
GameState.send_attack(aim_angle)
else:
print("[DungeonManager] No weapon equipped, using fists")
# No weapon or empty slot - use normal attack (fists)
GameState.send_attack(aim_angle)
# Inventory toggle (I key)
if Input.is_action_just_pressed("inventory"):
@@ -365,3 +404,129 @@ func _update_loot_chests():
func _on_tiles_updated(tiles: Array):
if visual_renderer:
visual_renderer.update_tiles(tiles)
# ===== Projectile Event Handlers =====
func _on_projectile_spawned(data: Dictionary):
print("[DungeonManager] Projectile spawned event received: ", data)
if projectile_scene == null:
print("[DungeonManager] ERROR: projectile_scene is null!")
return
if projectiles_container == null:
print("[DungeonManager] ERROR: projectiles_container is null!")
return
var proj_id = data.get("id", -1)
if proj_id == -1:
print("[DungeonManager] ERROR: Invalid projectile ID")
return
print("[DungeonManager] Creating projectile instance for ID: ", proj_id)
# Create projectile instance
var projectile = projectile_scene.instantiate()
projectile.name = "Projectile_" + str(proj_id)
projectiles_container.add_child(projectile)
print("[DungeonManager] Projectile node created and added to container")
# Initialize projectile with data
if projectile.has_method("initialize"):
projectile.initialize(data)
print("[DungeonManager] Projectile initialized")
else:
print("[DungeonManager] ERROR: Projectile has no initialize method!")
# Store in tracking dictionary
projectiles[proj_id] = projectile
print("[DungeonManager] Projectile ", proj_id, " tracked. Total projectiles: ", projectiles.size())
func _on_projectile_hit(data: Dictionary):
var proj_id = data.get("projectileId", -1)
if proj_id == -1:
return
# Remove projectile on hit
if projectiles.has(proj_id):
var projectile = projectiles[proj_id]
if is_instance_valid(projectile):
projectile.queue_free()
projectiles.erase(proj_id)
print("[DungeonManager] Projectile ", proj_id, " removed on hit")
# TODO: Play hit effect at projectile position
func _on_projectile_expired(data: Dictionary):
var proj_id = data.get("projectileId", -1)
if proj_id == -1:
return
# Remove projectile on expiration
if projectiles.has(proj_id):
var projectile = projectiles[proj_id]
if is_instance_valid(projectile):
projectile.queue_free()
projectiles.erase(proj_id)
var reason = data.get("reason", "unknown")
print("[DungeonManager] Projectile ", proj_id, " expired (", reason, ")")
func _on_damage_number(data: Dictionary):
if not damage_number_scene:
print("[DungeonManager] Damage number scene not loaded!")
return
var damage = data.get("damage", 0)
print("[DungeonManager] Damage event received: ", data)
print("[DungeonManager] Damage value: ", damage)
if damage <= 0:
print("[DungeonManager] Damage is 0 or negative, skipping")
return
# Get target position - need to find the entity's position
var target_type = data.get("targetType", "")
var target_id = data.get("targetId", 0)
var target_pos = Vector2.ZERO
var found_target = false
# Find target entity to get position
if target_type == "mob":
# Check mobs container
for mob_node in mobs_container.get_children():
var mob_id = mob_node.mob_data.get("id", mob_node.mob_data.get("Id", -1))
if mob_id == target_id:
target_pos = mob_node.position
found_target = true
break
elif target_type == "player":
# Check if it's the local player
if target_id == GameState.character.id:
target_pos = player_node.position
found_target = true
else:
# Check other players
for player in players_container.get_children():
if player.player_id == target_id:
target_pos = player.position
found_target = true
break
if not found_target:
return
# Create damage number
var dmg_number = damage_number_scene.instantiate()
add_child(dmg_number)
dmg_number.position = target_pos
# Determine color based on damage flags
var color = Color.RED # Default red for normal damage
if data.get("wasResisted", false):
color = Color(0.7, 0.7, 0.7) # Gray for resisted
elif data.get("wasWeakness", false):
color = Color(1.0, 0.5, 0.0) # Orange for weakness
dmg_number.initialize(damage, color)
+4 -4
View File
@@ -252,7 +252,7 @@ func _build_from_new_format():
_animated_sprite.position = Vector2.ZERO
_using_fallback = false
print("[MobVisual] NEW FORMAT - Built sprite with animations: %s" % [sprite_frames.get_animation_names()])
#print("[MobVisual] NEW FORMAT - Built sprite with animations: %s" % [sprite_frames.get_animation_names()])
# Hide fallback
if fallback_sprite:
@@ -441,7 +441,7 @@ func _play_animation(state: String, direction: String):
# Only log and play if animation changed
if anim_name != _last_animation:
print("[MobVisual] Playing animation: %s (state=%s, dir=%s)" % [anim_name, state, direction])
#print("[MobVisual] Playing animation: %s (state=%s, dir=%s)" % [anim_name, state, direction])
_last_animation = anim_name
_animated_sprite.play(anim_name)
@@ -455,8 +455,8 @@ func _play_animation(state: String, direction: String):
return
# No animation found
print("[MobVisual] No animation found for state=%s, dir=%s. Tried: %s" % [state, direction, names_to_try])
print("[MobVisual] Available animations: %s" % [frames.get_animation_names()])
#print("[MobVisual] No animation found for state=%s, dir=%s. Tried: %s" % [state, direction, names_to_try])
#print("[MobVisual] Available animations: %s" % [frames.get_animation_names()])
func _alt_direction(dir: String) -> String:
match dir:
+81
View File
@@ -0,0 +1,81 @@
extends Node2D
## Projectile instance - represents a flying arrow, bolt, or thrown weapon
## Handles visual rendering and smooth movement interpolation
var sprite: Sprite2D = null
var projectile_id: int = -1
var source_type: String = "" # "player" or "mob"
var source_id: int = 0
var velocity: Vector2 = Vector2.ZERO
var sprite_key: String = ""
func _ready():
# Create sprite node
sprite = Sprite2D.new()
sprite.name = "Sprite"
add_child(sprite)
# Set default fallback
_use_fallback_sprite()
func _use_fallback_sprite():
if not sprite:
return
# Create a simple circular fallback sprite
if has_node("/root/SpriteGenerator"):
var sprite_gen = get_node("/root/SpriteGenerator")
sprite.texture = sprite_gen.get_circle()
sprite.modulate = Color(1.0, 0.8, 0.2) # Yellowish for projectiles
sprite.scale = Vector2(0.3, 0.3)
else:
# If no SpriteGenerator, just leave it invisible for now
print("[Projectile] Warning: No SpriteGenerator available for fallback")
func _load_sprite():
if not sprite:
return
# Try to load projectile sprite from CDN if UpdateManager exists
if sprite_key and not sprite_key.is_empty() and has_node("/root/UpdateManager"):
var update_manager = get_node("/root/UpdateManager")
var texture = update_manager.load_texture(sprite_key)
if texture:
sprite.texture = texture
sprite.modulate = Color.WHITE # Reset modulate
sprite.scale = Vector2(0.5, 0.5) # Scale down projectiles
else:
print("[Projectile] Failed to load sprite: ", sprite_key)
_use_fallback_sprite()
else:
_use_fallback_sprite()
func _process(delta):
# Move projectile based on velocity (client-side prediction)
if velocity.length() > 0:
position += velocity * delta
rotation = velocity.angle()
func initialize(data: Dictionary):
projectile_id = data.get("id", -1)
source_type = data.get("sourceType", "")
source_id = data.get("sourceId", 0)
position.x = data.get("x", 0)
position.y = data.get("y", 0)
velocity.x = data.get("vx", 0)
velocity.y = data.get("vy", 0)
sprite_key = data.get("sprite", "")
# Set rotation based on initial velocity
if velocity.length() > 0:
rotation = velocity.angle()
# Load sprite after initialization
_load_sprite()
print("[Projectile] Initialized projectile ", projectile_id, " at (", position.x, ", ", position.y, ") with velocity (", velocity.x, ", ", velocity.y, ")")
+1
View File
@@ -0,0 +1 @@
uid://b8kuuhbv0mkvo
+55 -9
View File
@@ -5,17 +5,36 @@ extends CanvasLayer
@onready var inventory_grid = $PanelContainer/VBoxContainer/Content/BagSection/InventoryGrid
@onready var gold_label = $PanelContainer/VBoxContainer/Footer/GoldLabel
const EQUIPMENT_SLOTS = ["weapon", "offhand", "helm", "chest", "gloves", "legs", "boots", "ring1", "ring2"]
const EQUIPMENT_SLOTS = ["weapon", "offhand", "helm", "chest", "gloves", "legs", "boots", "necklace", "ring1", "ring2", "quiver"]
# Emoji fallbacks for equipment slots (used when CDN texture not available)
const EQUIPMENT_ICONS = {
"weapon": "⚔️",
"offhand": "🛡️",
"offhand": "🛡️",
"helm": "🎩",
"chest": "👕",
"gloves": "🧤",
"legs": "👖",
"boots": "👢",
"necklace": "📿",
"ring1": "💍",
"ring2": "💍"
"ring2": "💍",
"quiver": "🏹"
}
# CDN paths for equipment slot background icons
const EQUIPMENT_SLOT_TEXTURES = {
"weapon": "textures/ui/slots/mainhand.png",
"offhand": "textures/ui/slots/offhand.png",
"helm": "textures/ui/slots/head.png",
"chest": "textures/ui/slots/chest.png",
"gloves": "textures/ui/slots/gloves.png",
"legs": "textures/ui/slots/legs.png",
"boots": "textures/ui/slots/boots.png",
"necklace": "textures/ui/slots/neck.png",
"ring1": "textures/ui/slots/ring.png",
"ring2": "textures/ui/slots/ring.png",
"quiver": "textures/ui/slots/back.png"
}
const RARITY_COLORS = {
@@ -165,18 +184,39 @@ func _refresh_inventory():
for slot_name in EQUIPMENT_SLOTS:
if equipment_slots.has(slot_name):
var item = GameState.equipment.get(slot_name)
_update_slot(equipment_slots[slot_name], item, EQUIPMENT_ICONS.get(slot_name, "?"))
_update_slot(equipment_slots[slot_name], item, EQUIPMENT_ICONS.get(slot_name, "?"), slot_name)
func _update_slot(slot: Button, item, default_text: String = ""):
func _update_slot(slot: Button, item, default_text: String = "", slot_name: String = ""):
# Clear any existing children (sprites, labels)
for child in slot.get_children():
child.queue_free()
if item == null or (item is Dictionary and item.is_empty()):
slot.text = default_text
# Empty slot: try to load CDN slot texture, fall back to emoji
slot.set_meta("item", null)
slot.add_theme_stylebox_override("normal", _create_slot_style(Color(0.15, 0.15, 0.2)))
# Try to load slot icon from CDN if this is an equipment slot
if slot_name != "" and EQUIPMENT_SLOT_TEXTURES.has(slot_name) and UpdateManager:
var slot_texture_path = EQUIPMENT_SLOT_TEXTURES.get(slot_name)
var texture = UpdateManager.load_texture(slot_texture_path)
if texture:
var sprite = TextureRect.new()
sprite.texture = texture
sprite.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
sprite.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
sprite.custom_minimum_size = Vector2(32, 32)
sprite.anchors_preset = Control.PRESET_CENTER
sprite.position = Vector2(8, 8) # Center in 48x48 slot
sprite.modulate = Color(1, 1, 1, 0.3) # Dim the slot icon to show it's empty
slot.add_child(sprite)
slot.text = "" # Clear emoji text since we have a texture
return
# Fall back to emoji if CDN texture not available
slot.text = default_text
else:
# Equipped item: show the item's sprite, NOT the slot icon
slot.text = "" # Clear text, we'll use sprite instead
slot.set_meta("item", item)
@@ -207,9 +247,15 @@ func _update_slot(slot: Button, item, default_text: String = ""):
if not has_sprite:
slot.text = _get_item_emoji(item)
# Add stack count label if quantity > 1
# Add stack count label if quantity > 1 OR if this is equipped ammunition/quiver
var quantity = item.get("quantity", item.get("Quantity", 1))
if quantity > 1:
var show_count = quantity > 1
# Always show count for equipped quiver or ammunition slots
if slot_name == "quiver" and quantity >= 1:
show_count = true
if show_count:
var count_label = Label.new()
count_label.text = str(quantity)
count_label.add_theme_font_size_override("font_size", 10)