可复用玩家状态机
This commit is contained in:
+10
-109
@@ -1,17 +1,19 @@
|
||||
extends CharacterBody3D
|
||||
## 第三人称控制器(胶囊体占位)
|
||||
## 第三人称控制器:只管「怎么动」—— 输入、移动物理、相机、血条、联机分叉。
|
||||
## 表现层(动画)在 Body/PlayerAnimator 里,本文件不认识任何片段名。
|
||||
##
|
||||
## 场景结构:
|
||||
## Player (CharacterBody3D) ← 只负责移动与碰撞,自身不旋转
|
||||
## ├─ Collision (CollisionShape3D, CapsuleShape3D)
|
||||
## ├─ Body (Node3D) ← 视觉层,朝移动方向转身;换角色模型时挂在它下面
|
||||
## │ ├─ PlayerAnimator (PlayerAnimator.gd) ← 动作状态机:只读运动、只写动画
|
||||
## │ └─ character-male-e2 (Node3D)
|
||||
## │ ├─ character-male-e/Skeleton3D ← 骨骼 + 蒙皮网格(character-male-e.glb)
|
||||
## │ └─ AnimationPlayer ← 动作库:idle / walk / sprint / jump / fall
|
||||
## │ └─ AnimationPlayer ← 动作库,由 PlayerAnimator 驱动
|
||||
## ├─ CameraRig (Node3D) ← 承担偏航 yaw,独立于本体旋转
|
||||
## │ └─ SpringArm (SpringArm3D) ← 承担俯仰 pitch,自动避障
|
||||
## │ └─ Camera (Camera3D)
|
||||
## ├─ Sync (MultiplayerSynchronizer) ← 同步 position、Body.rotation、health、anim_state、anim_speed
|
||||
## ├─ Sync (MultiplayerSynchronizer) ← 同步 position、Body.rotation、health、动画状态
|
||||
## └─ HealthLabel (Label3D) ← 头顶血条(节点配置,不是代码建的)
|
||||
##
|
||||
## 操作:WASD/方向键移动,鼠标转视角,Shift 疾跑,空格跳跃,Esc 释放/锁定鼠标
|
||||
@@ -19,22 +21,6 @@ extends CharacterBody3D
|
||||
## 跳跃输入缓冲帧数(输入事件在渲染帧到达,物理帧读取,避免漏跳)
|
||||
const JUMP_BUFFER_FRAMES: int = 6
|
||||
|
||||
## 角色动作状态。权威端每物理帧算一次,再靠 Sync 复制给远端回放。
|
||||
enum AnimState { IDLE, WALK, SPRINT, JUMP, FALL }
|
||||
|
||||
## 状态 → 片段名。名字取自 character-male-e.glb 的动作库,改名要同步改这里。
|
||||
const ANIM_CLIPS: Dictionary = {
|
||||
AnimState.IDLE: "idle",
|
||||
AnimState.WALK: "walk",
|
||||
AnimState.SPRINT: "sprint",
|
||||
AnimState.JUMP: "jump",
|
||||
AnimState.FALL: "fall",
|
||||
}
|
||||
|
||||
## 需要循环的状态。glb 里每个片段的 loop_mode 都是 NONE,
|
||||
## 不补循环的话 idle/walk/sprint 播一遍就定在最后一帧。
|
||||
const ANIM_LOOPED: Array[int] = [AnimState.IDLE, AnimState.WALK, AnimState.SPRINT]
|
||||
|
||||
@export_group("属性")
|
||||
## 血量
|
||||
@export var health: int = 100:
|
||||
@@ -64,23 +50,14 @@ const ANIM_LOOPED: Array[int] = [AnimState.IDLE, AnimState.WALK, AnimState.SPRIN
|
||||
## 最高仰角(向上看)
|
||||
@export var pitch_max_deg: float = 45.0
|
||||
|
||||
@export_group("动画")
|
||||
## 动作切换的交叉淡入时间(秒)。0 为硬切
|
||||
@export var anim_blend_time: float = 0.15
|
||||
## 低于此水平速度就视为站立(米/秒)
|
||||
@export var anim_idle_threshold: float = 0.2
|
||||
## 播放倍率下限:被墙抵住、起步那一瞬,脚步不该慢到像在滑冰
|
||||
@export var anim_speed_scale_min: float = 0.65
|
||||
## 播放倍率上限:防止速度被外力拉高时脚步快到抽搐
|
||||
@export var anim_speed_scale_max: float = 1.6
|
||||
|
||||
@onready var body: Node3D = $Body
|
||||
@onready var camera_rig: Node3D = $CameraRig
|
||||
@onready var spring_arm: SpringArm3D = $CameraRig/SpringArm
|
||||
## 头顶血条是 player.tscn 里的 Label3D 节点(3D 世界里的文字,会跟着角色走)
|
||||
@onready var _health_label: Label3D = $HealthLabel
|
||||
|
||||
@onready var animation_player: AnimationPlayer = $"Body/character-male-e2/AnimationPlayer"
|
||||
## 动画状态机(挂在 Body 下)。只把「运动结果」交给它,也只知道它会自己播动画。
|
||||
@onready var animator: PlayerAnimator = $Body/PlayerAnimator
|
||||
|
||||
var _gravity: float = float(ProjectSettings.get_setting("physics/3d/default_gravity", 9.8))
|
||||
var _yaw: float = 0.0
|
||||
@@ -89,30 +66,10 @@ var _jump_buffer: int = 0
|
||||
## 本节点是否由本机玩家操控。由世界节点在生成时设置 authority 决定,见 world/main.gd。
|
||||
var _is_local: bool = true
|
||||
|
||||
## 当前动作状态(AnimState)。
|
||||
## 权威端每物理帧写一次,Sync 把它复制给远端 —— 远端物理与输入都关着,
|
||||
## 只有靠这个值才知道该播哪个片段。
|
||||
var anim_state: int = AnimState.IDLE:
|
||||
set(value):
|
||||
if anim_state == value:
|
||||
return
|
||||
anim_state = value
|
||||
_apply_anim_state()
|
||||
|
||||
## 当前播放倍率(1.0 = 片段原速)。
|
||||
## 同样要复制:远端只有 position,算不出真实速度,只能照抄权威端的倍率。
|
||||
var anim_speed: float = 1.0:
|
||||
set(value):
|
||||
value = clampf(value, anim_speed_scale_min, anim_speed_scale_max)
|
||||
anim_speed = value
|
||||
if animation_player != null:
|
||||
animation_player.speed_scale = value
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
_report_identity()
|
||||
# 本地端与远端都要跑:本地端播自己的动作,远端靠复制来的 anim_state 回放
|
||||
_prepare_animation()
|
||||
# 动画准备不在这里 —— PlayerAnimator 有自己的 _ready(),而子节点先于本节点 ready
|
||||
_is_local = is_multiplayer_authority()
|
||||
if not _is_local:
|
||||
# 远端玩家只是一具「回放身体」:
|
||||
@@ -200,7 +157,8 @@ func _physics_process(delta: float) -> void:
|
||||
|
||||
move_and_slide()
|
||||
|
||||
_update_animation()
|
||||
# 动画只读运动结果。控制器不认识任何片段名,动画器也不认识输入。
|
||||
animator.set_motion(velocity, is_on_floor(), Input.is_action_pressed("sprint"))
|
||||
|
||||
|
||||
func _refresh_health_label() -> void:
|
||||
@@ -211,63 +169,6 @@ func _refresh_health_label() -> void:
|
||||
_health_label.text = "HP %d / 100" % health
|
||||
|
||||
|
||||
## 准备动作库。两个端点都要跑,且必须在本地/远端分支之前。
|
||||
func _prepare_animation() -> void:
|
||||
if animation_player == null:
|
||||
push_warning("%s 下没有 AnimationPlayer,角色不会有动画" % name)
|
||||
return
|
||||
for state in ANIM_LOOPED:
|
||||
var clip: String = ANIM_CLIPS[state]
|
||||
if not animation_player.has_animation(clip):
|
||||
continue
|
||||
animation_player.get_animation(clip).loop_mode = Animation.LOOP_LINEAR
|
||||
# 先站在 idle。之后 state 不变时 setter 不会重进去,所以这一句不能省。
|
||||
animation_player.play(ANIM_CLIPS[AnimState.IDLE], 0.0)
|
||||
|
||||
|
||||
## 权威端每物理帧调用:从本帧的真实运动推出动作状态与播放倍率。
|
||||
## 只读 velocity / is_on_floor(),不写任何物理量。
|
||||
func _update_animation() -> void:
|
||||
var h_speed := Vector2(velocity.x, velocity.z).length()
|
||||
|
||||
var next_state: int
|
||||
if not is_on_floor():
|
||||
# 上升用 jump、越过顶点用 fall。jump 片段长 0.5s,
|
||||
# 恰好约等于 jump_velocity 5 / 重力 9.8 的上升时间。
|
||||
next_state = AnimState.JUMP if velocity.y > 0.0 else AnimState.FALL
|
||||
elif h_speed < anim_idle_threshold:
|
||||
next_state = AnimState.IDLE
|
||||
elif Input.is_action_pressed("sprint"):
|
||||
next_state = AnimState.SPRINT
|
||||
else:
|
||||
next_state = AnimState.WALK
|
||||
|
||||
# 先把倍率写下去,再切片段 —— 顺序反了会让新片段用一帧旧倍率。
|
||||
var ref := _anim_reference_speed(next_state)
|
||||
anim_speed = h_speed / ref if ref > 0.0 else 1.0
|
||||
anim_state = next_state # setter 负责切片段
|
||||
|
||||
|
||||
## 该状态对应的「设计速度」。片段在 ref 速度下按 1.0 倍播放,快慢全靠比例缩。
|
||||
func _anim_reference_speed(state: int) -> float:
|
||||
match state:
|
||||
AnimState.WALK:
|
||||
return walk_speed
|
||||
AnimState.SPRINT:
|
||||
return sprint_speed
|
||||
_:
|
||||
return 0.0
|
||||
|
||||
|
||||
func _apply_anim_state() -> void:
|
||||
if animation_player == null:
|
||||
return
|
||||
var clip: String = ANIM_CLIPS.get(anim_state, "")
|
||||
if clip.is_empty() or not animation_player.has_animation(clip):
|
||||
return
|
||||
animation_player.play(clip, anim_blend_time)
|
||||
|
||||
|
||||
## 关卡 0 的临时自检:把「我这一端」和「这个节点」分层打印出来。
|
||||
## 联机框架调通后可以整段删掉(连同 _ready() 里的那一行调用)。
|
||||
func _report_identity() -> void:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
[gd_scene format=4 uid="uid://bekuuw153mv03"]
|
||||
|
||||
[ext_resource type="Script" uid="uid://f5ptp3is4agf" path="res://character/player/player.gd" id="1_gtsfv"]
|
||||
[ext_resource type="Script" uid="uid://roaqmma0vjon" path="res://character/player/player_animator.gd" id="3_g20gq"]
|
||||
[ext_resource type="Texture2D" uid="uid://cq3awe0wjqsih" path="res://character/player/assets/Textures/colormap.png" id="3_gtsfv"]
|
||||
[ext_resource type="SceneReplicationConfig" uid="uid://c4ubbxjfrrs47" path="res://character/player/player_sync.tres" id="3_wu8e1"]
|
||||
|
||||
@@ -2796,6 +2797,9 @@ skeleton = NodePath("..")
|
||||
[node name="AnimationPlayer" type="AnimationPlayer" parent="Body/character-male-e2" unique_id=1443249442]
|
||||
libraries/ = SubResource("AnimationLibrary_muffn")
|
||||
|
||||
[node name="PlayerAnimator" type="Node" parent="Body" unique_id=390989323]
|
||||
script = ExtResource("3_g20gq")
|
||||
|
||||
[node name="Sync" type="MultiplayerSynchronizer" parent="." unique_id=1979575210]
|
||||
replication_config = ExtResource("3_wu8e1")
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
extends Node
|
||||
class_name PlayerAnimator
|
||||
## 角色动作状态机 —— 只负责「把运动状态翻译成播放哪段动画」,完全不碰移动。
|
||||
##
|
||||
## 挂在 Player/Body 下,与具体模型解耦:换角色模型只要在检视面板重新指定
|
||||
## animation_player(或让它自动找),代码里没有任何硬编码的节点路径。
|
||||
##
|
||||
## 对外接口只有一个:set_motion()。方向、加速度、重力、输入全归控制器管;
|
||||
## 本组件只读入一个「运动快照」,输出到 AnimationPlayer。反向不回写任何东西。
|
||||
##
|
||||
## 为什么状态与倍率必须是可复制属性:
|
||||
## 远端玩家物理与输入都关着,手里只有 position 和 Body.rotation,
|
||||
## 算不出水平速度,也分不清是上升还是下落。所以权威端把结论复制过去,
|
||||
## 远端只在 setter 里回放。
|
||||
## 对应的同步条目(Sync.root_path = "..",即 Player 节点):
|
||||
## Body/PlayerAnimator:anim_state
|
||||
## Body/PlayerAnimator:anim_speed
|
||||
|
||||
## 角色动作状态。权威端每物理帧算一次,再靠 Sync 复制给远端回放。
|
||||
enum AnimState { IDLE, WALK, SPRINT, JUMP, FALL }
|
||||
|
||||
## 状态 → 片段名。取自 character-male-e.glb 的动作库,换动作库改这里。
|
||||
const ANIM_CLIPS: Dictionary = {
|
||||
AnimState.IDLE: "idle",
|
||||
AnimState.WALK: "walk",
|
||||
AnimState.SPRINT: "sprint",
|
||||
AnimState.JUMP: "jump",
|
||||
AnimState.FALL: "fall",
|
||||
}
|
||||
|
||||
## 需要循环的状态。glb 里每个片段的 loop_mode 都是 NONE,
|
||||
## 不补循环的话 idle/walk/sprint 播一遍就定在最后一帧。
|
||||
const ANIM_LOOPED: Array[int] = [AnimState.IDLE, AnimState.WALK, AnimState.SPRINT]
|
||||
|
||||
@export_group("接线")
|
||||
## 要驱动的 AnimationPlayer。留空则在本节点的兄弟子树里自动找一个。
|
||||
## 换模型后这里重新指一下即可 —— 这也是它能脱离具体模型的原因。
|
||||
@export var animation_player: AnimationPlayer
|
||||
|
||||
@export_group("播放")
|
||||
## 动作切换的交叉淡入时间(秒)。0 为硬切
|
||||
@export var blend_time: float = 0.15
|
||||
## 低于此水平速度就视为站立(米/秒)
|
||||
@export var idle_threshold: float = 0.2
|
||||
## 播放倍率下限:被墙抵住、起步那一瞬,脚步不该慢到像在滑冰
|
||||
@export var speed_scale_min: float = 0.65
|
||||
## 播放倍率上限:防止速度被外力拉高时脚步快到抽搐
|
||||
@export var speed_scale_max: float = 1.6
|
||||
|
||||
@export_group("片段基准速度")
|
||||
## walk 片段在多少米/秒下按 1.0 倍播放。这是片段自身的属性,不是控制器的手感参数:
|
||||
## 控制器把跑速调到 6 m/s 时,这段动画自然播成 1.2 倍,脚步自动跟上,无需同步改两边。
|
||||
@export var walk_ref_speed: float = 5.0
|
||||
## sprint 片段的基准速度(米/秒)
|
||||
@export var sprint_ref_speed: float = 8.5
|
||||
|
||||
## 当前动作状态(AnimState)。权威端每物理帧写一次,Sync 复制给远端。
|
||||
var anim_state: int = AnimState.IDLE:
|
||||
set(value):
|
||||
if anim_state == value:
|
||||
return
|
||||
anim_state = value
|
||||
_play(ANIM_CLIPS.get(anim_state, ""), blend_time)
|
||||
|
||||
## 当前播放倍率(1.0 = 片段原速)。
|
||||
## 同样要复制:远端只有 position,算不出真实速度,只能照抄权威端的倍率。
|
||||
var anim_speed: float = 1.0:
|
||||
set(value):
|
||||
value = clampf(value, speed_scale_min, speed_scale_max)
|
||||
anim_speed = value
|
||||
if animation_player != null:
|
||||
animation_player.speed_scale = value
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
if animation_player == null:
|
||||
animation_player = _auto_find_animation_player()
|
||||
if animation_player == null:
|
||||
push_warning("%s 没绑定 AnimationPlayer,角色不会有动画" % get_path())
|
||||
return
|
||||
_patch_loop_modes()
|
||||
# 同步可能在 _ready() 之前就把 anim_state 写进来了 —— 那时 animation_player 还是 null,
|
||||
# setter 空跑了一趟。所以这里按「当前状态」补播一遍,不能写死 idle。
|
||||
_play(ANIM_CLIPS.get(anim_state, ""), 0.0)
|
||||
|
||||
|
||||
# ---------------- 对外接口 ----------------
|
||||
|
||||
## 控制器每物理帧调用一次(放在 move_and_slide() 之后)。
|
||||
## 只读入运动快照,不回写任何物理量 —— 这就是「单向耦合」的边界。
|
||||
func set_motion(velocity: Vector3, on_floor: bool, sprinting: bool = false) -> void:
|
||||
var state := _resolve_state(velocity, on_floor, sprinting)
|
||||
# 先写倍率再切片段 —— 顺序反了会让新片段用一帧旧倍率。
|
||||
anim_speed = _speed_scale_for(state, velocity)
|
||||
anim_state = state # setter 负责切片段
|
||||
|
||||
|
||||
## 当前正在播的片段名。调试与测试用。
|
||||
func current_clip() -> String:
|
||||
if animation_player == null:
|
||||
return ""
|
||||
return str(animation_player.current_animation)
|
||||
|
||||
|
||||
# ---------------- 内部 ----------------
|
||||
|
||||
func _resolve_state(velocity: Vector3, on_floor: bool, sprinting: bool) -> int:
|
||||
if not on_floor:
|
||||
# 上升用 jump、越过顶点用 fall。jump 片段长 0.5s,
|
||||
# 恰好约等于 jump_velocity 5 / 重力 9.8 的上升时间。
|
||||
return AnimState.JUMP if velocity.y > 0.0 else AnimState.FALL
|
||||
if Vector2(velocity.x, velocity.z).length() < idle_threshold:
|
||||
return AnimState.IDLE
|
||||
return AnimState.SPRINT if sprinting else AnimState.WALK
|
||||
|
||||
|
||||
## 播放倍率 = 实际水平速度 / 该片段的基准速度。
|
||||
## 只有循环的移动动作参与缩放,跳跃/下落/站立一律原速。
|
||||
func _speed_scale_for(state: int, velocity: Vector3) -> float:
|
||||
var ref := 0.0
|
||||
match state:
|
||||
AnimState.WALK:
|
||||
ref = walk_ref_speed
|
||||
AnimState.SPRINT:
|
||||
ref = sprint_ref_speed
|
||||
_:
|
||||
return 1.0
|
||||
if ref <= 0.0:
|
||||
return 1.0
|
||||
return Vector2(velocity.x, velocity.z).length() / ref
|
||||
|
||||
|
||||
func _play(clip: String, blend: float) -> void:
|
||||
if animation_player == null or clip.is_empty():
|
||||
return
|
||||
if not animation_player.has_animation(clip):
|
||||
return
|
||||
animation_player.play(clip, blend)
|
||||
|
||||
|
||||
## 兜底:在同一层视觉节点里找一个 AnimationPlayer。只在没接线时生效。
|
||||
func _auto_find_animation_player() -> AnimationPlayer:
|
||||
var parent := get_parent()
|
||||
if parent == null:
|
||||
return null
|
||||
return parent.find_child("AnimationPlayer", true, false) as AnimationPlayer
|
||||
|
||||
|
||||
func _patch_loop_modes() -> void:
|
||||
for state in ANIM_LOOPED:
|
||||
var clip: String = ANIM_CLIPS[state]
|
||||
if not animation_player.has_animation(clip):
|
||||
continue
|
||||
animation_player.get_animation(clip).loop_mode = Animation.LOOP_LINEAR
|
||||
@@ -0,0 +1 @@
|
||||
uid://roaqmma0vjon
|
||||
@@ -10,9 +10,9 @@ properties/1/replication_mode = 1
|
||||
properties/2/path = NodePath(".:health")
|
||||
properties/2/spawn = true
|
||||
properties/2/replication_mode = 1
|
||||
properties/3/path = NodePath(".:anim_state")
|
||||
properties/3/path = NodePath("Body/PlayerAnimator:anim_state")
|
||||
properties/3/spawn = true
|
||||
properties/3/replication_mode = 1
|
||||
properties/4/path = NodePath(".:anim_speed")
|
||||
properties/4/path = NodePath("Body/PlayerAnimator:anim_speed")
|
||||
properties/4/spawn = true
|
||||
properties/4/replication_mode = 1
|
||||
|
||||
Reference in New Issue
Block a user