Files
windroost/p2_godot_sample/scripts/unit_view.gd
T

264 lines
7.6 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 reduced_motion := false
var low_power := false
var _breath_tween: Tween
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, no_motion: bool = false) -> bool:
character_id = id
reduced_motion = no_motion
_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
if reduced_motion:
# Keep the current frame static; state changes still swap the art.
return
_elapsed += delta
var fps := float(state.get("fps", 8))
# Authored idle manifests use 3 fps (4 frames = a 1.3s loop), which reads
# as a frozen sprite at play size. A 6 fps floor keeps the breathing alive
# without touching generated asset data. One-shot attack/hit states keep
# their authored pacing.
if _current == "idle":
fps = maxf(fps, 6.0)
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 set_reduced_motion(value: bool) -> void:
reduced_motion = value
if value:
_stop_breathing()
# A one-shot state (attack/hit) mid-play would freeze forever on its
# current frame because _process no longer advances frames in reduced
# motion. Snap it back to its fallback so the sprite returns to rest.
if not _current.is_empty() and _current != "idle" and _states.has("idle"):
var fallback := _returning_to if not _returning_to.is_empty() else "idle"
_returning_to = ""
set_state(fallback)
elif _current == "idle" and not low_power:
_start_breathing()
## Low power removes continuous ambient motion but never changes the frame
## state or gameplay outcome. Mirrors FeedbackService.configure(low_power).
func set_low_power(value: bool) -> void:
low_power = value
if value:
_stop_breathing()
elif not reduced_motion and _current == "idle":
_start_breathing()
func _exit_tree() -> void:
_stop_breathing()
func is_breathing() -> bool:
return _breath_tween != null and _breath_tween.is_valid()
func current_state_for_test() -> String:
return _current
func set_frame_for_test(frame: int) -> void:
if _states.has(_current):
var frames: Array = _states[_current].get("frames", [])
if frames.size() > 0:
_frame_index = clampi(frame, 0, frames.size() - 1)
_apply_frame()
func current_frame() -> int:
return _frame_index
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))
if _current == "idle" and not reduced_motion and _breath_tween == null:
_start_breathing()
elif _current != "idle":
_stop_breathing()
func _start_breathing() -> void:
if _sprite == null or low_power:
return
_stop_breathing()
# Subtle idle breathing: a 2.5% vertical squash. Continuous, eased, and
# returns to base; disabled under reduced motion.
var base_scale := Vector2.ONE
_sprite.scale = base_scale
_breath_tween = create_tween()
_breath_tween.set_loops()
_breath_tween.tween_property(_sprite, "scale", Vector2(1.0, 1.025), 0.85) \
.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
_breath_tween.tween_property(_sprite, "scale", base_scale, 0.85) \
.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
func _stop_breathing() -> void:
if _breath_tween != null and _breath_tween.is_valid():
_breath_tween.kill()
_breath_tween = null
if _sprite != null and is_instance_valid(_sprite):
_sprite.scale = Vector2.ONE