Files
windroost/p2_godot_sample/scripts/unit_view.gd
T
wushenghua a0c590deec feat: add animated units, real touch input and the runtime economy loop
Continues the MVP work from the UI and numbers baseline.

Animation. The frame runs were already in the repository but had never been
packed for runtime use. pack_animation_strip.py now derives one shared scale
and one shared foot line from the union of every frame in a state, so the
character does not jitter between frames; H01 idle/attack, EG01 idle/hit and
B01 idle/hit are packed as transparent fixed-grid atlases. UnitView plays
them with the node origin on the foot line, loops idle, plays hit once and
falls back, and flashes on damage. Content-to-art bindings live in the
content fixture, so no character id is hardcoded in the HUD.

Touch. The previous HUD used gui_input callbacks, which is not proof of a
mobile input path. run_touch_test.sh now feeds InputEventScreenTouch through
Input.parse_input_event and checks that taps on the tap toggle, an enemy card
and the storm button produce the right events on the right tick. It also
caught a real bug: Godot emulates mouse presses from touches, so one tap was
firing both handlers; enemy taps are now debounced.

Economy. The paper model had the reward and upgrade curves but the runtime
only subtracted gold from a balance that was always zero. The scene now owns
permanent progress: victory grants the reward from the shared rules, upgrades
cost a growing amount, hero DPS rises per level, and the next battle is
created with the upgraded roster DPS. run_economy_loop_test.sh proves four
N01 clears pay for the first upgrade and that duplicate grants and losses
behave correctly. The economy pacing was left at four wins rather than
weakening it to satisfy the test.

tools/run_p2_checks.sh now runs 11 gates; all pass. PRODUCTION/38 records
P2-IMP-02/03 and P2-BAT-02 as PASS. Remaining P2 holds: profiler/visual
limit, shield-break and ultimate VFX, real-device safe area and performance.
2026-11-16 23:30:49 +08:00

174 lines
4.8 KiB
GDScript

class_name UnitView
extends Node2D
## Runtime unit renderer for the battle stage.
##
## Each unit state is a fixed-grid animation atlas produced by
## `tools/pack_animation_strip.py`, with one shared scale and one shared foot
## line across all frames of that state. That is what keeps the character
## from jumping between frames.
##
## The node origin is the unit's foot line, so units can be placed by their
## ground position without any per-frame correction.
## Textures have to live inside the project to be imported, so the animation
## atlases are linked into `assets/` and addressed from there.
const CHARACTER_DIR := "res://assets/"
var character_id := ""
var _states: Dictionary = {}
var _sprite: Sprite2D
var _current := ""
var _frame_index := 0
var _elapsed := 0.0
var _returning_to := ""
var _flash_time := 0.0
var _flash_duration := 0.0
var _flash_color := Color(1, 1, 1, 1)
func _ready() -> void:
_ensure_sprite()
func _ensure_sprite() -> void:
if _sprite != null and is_instance_valid(_sprite):
return
_sprite = Sprite2D.new()
_sprite.name = "Art"
_sprite.centered = true
_sprite.texture_filter = CanvasItem.TEXTURE_FILTER_NEAREST
add_child(_sprite)
## Load one or more states for a character. Returns false when no state could
## be loaded, which means the unit has no approved art yet.
func configure(id: String, state_list: Array) -> bool:
character_id = id
_states.clear()
_ensure_sprite()
for state in state_list:
var loaded := _load_state(str(state))
if loaded:
_states[str(state)] = loaded
if _states.is_empty():
return false
if _states.has("idle"):
set_state("idle")
else:
set_state(str(_states.keys()[0]))
return true
func _load_state(state: String) -> Dictionary:
var base := "%s/%s_%s_anim" % [CHARACTER_DIR, character_id, state]
var manifest_path := base + ".manifest.json"
var texture_path := base + ".png"
var file := FileAccess.open(manifest_path, FileAccess.READ)
if file == null:
return {}
var parsed = JSON.parse_string(file.get_as_text())
file.close()
if not parsed is Dictionary:
return {}
var texture := load(texture_path) as Texture2D
if texture == null:
return {}
var frames: Array = []
for frame in parsed.get("frames", []):
var rect: Array = frame.get("atlas_rect", [])
if rect.size() != 4:
continue
frames.append(Rect2(float(rect[0]), float(rect[1]), float(rect[2]), float(rect[3])))
if frames.is_empty():
return {}
var cell: Array = parsed.get("cell_size", [96, 96])
var foot_y := float(parsed.get("foot_y", cell[1]))
return {
"texture": texture,
"frames": frames,
"fps": float(parsed.get("fps", 8)),
"loop": bool(parsed.get("loop", false)),
"cell": [float(cell[0]), float(cell[1])],
"foot_y": foot_y,
}
func has_state(state: String) -> bool:
return _states.has(state)
func set_state(state: String) -> void:
if not _states.has(state) or state == _current:
return
_current = state
_frame_index = 0
_elapsed = 0.0
_returning_to = ""
_apply_frame()
## Play a non-looping state once, then fall back to `fallback`.
func play_once(state: String, fallback: String = "idle") -> void:
if not _states.has(state):
return
_current = state
_frame_index = 0
_elapsed = 0.0
_returning_to = fallback
func flash(color: Color = Color(1, 1, 1, 1), duration: float = 0.12) -> void:
_flash_color = color
_flash_duration = duration
_flash_time = duration
func _process(delta: float) -> void:
if _states.is_empty():
return
if _flash_time > 0.0:
_flash_time = maxf(0.0, _flash_time - delta)
var ratio := _flash_time / maxf(0.001, _flash_duration)
_sprite.modulate = Color(1, 1, 1, 1).lerp(_flash_color, ratio)
else:
_sprite.modulate = Color(1, 1, 1, 1)
var state: Dictionary = _states.get(_current, {})
var frames: Array = state.get("frames", [])
if frames.size() <= 1:
return
_elapsed += delta
var fps := float(state.get("fps", 8))
var frame_duration := 1.0 / maxf(0.1, fps)
while _elapsed >= frame_duration:
_elapsed -= frame_duration
_frame_index += 1
if _frame_index >= frames.size():
if state.get("loop", false):
_frame_index = 0
else:
_frame_index = frames.size() - 1
if not _returning_to.is_empty() and _states.has(_returning_to):
var fallback := _returning_to
_returning_to = ""
set_state(fallback)
return
_apply_frame()
func _apply_frame() -> void:
var state: Dictionary = _states.get(_current, {})
var frames: Array = state.get("frames", [])
if frames.is_empty():
return
_sprite.texture = state.get("texture")
_sprite.region_enabled = true
_sprite.region_rect = frames[_frame_index]
var cell: Array = state.get("cell", [96.0, 96.0])
var foot_y := float(state.get("foot_y", cell[1]))
# The node origin is the foot line, so the art has to be lifted by the
# distance between the cell centre and the foot line.
_sprite.offset = Vector2(0.0, -(foot_y - float(cell[1]) * 0.5))