角色动画

This commit is contained in:
2026-10-02 09:32:11 +08:00
parent 5173b45066
commit d367c8370b
10 changed files with 240 additions and 68 deletions
+17 -14
View File
@@ -1,15 +1,13 @@
extends CharacterBody3D
## 第三人称控制器:只管「怎么动」—— 输入、移动物理、相机、血条、联机分叉。
## 表现层(动画)在 Body/PlayerAnimator 里,本文件不认识任何片段名。
## 表现层(动画)在 Body/AnimationPlayer 上(挂 player_animator.gd),本文件不认识任何片段名。
##
## 场景结构:
## Player (CharacterBody3D) ← 只负责移动与碰撞,自身不旋转
## ├─ Collision (CollisionShape3D, CapsuleShape3D)
## ├─ Body (Node3D) ← 视觉层,朝移动方向转身;换角色模型时挂在它下面
## │ ├─ PlayerAnimator (PlayerAnimator.gd) ← 动作状态机:只读运动、只写动画
## │ └─ character-male-e2 (Node3D)
## │ ├─ character-male-e/Skeleton3D ← 骨骼 + 蒙皮网格(character-male-e.glb)
## │ └─ AnimationPlayer ← 动作库,由 PlayerAnimator 驱动
## │ ├─ mouse (Node3D) ← 模型(mouse.glb):MouseRig/Skeleton3D + 各部位 MeshInstance3D
## │ └─ AnimationPlayer ← 动作库 + 表现层(挂 player_animator.gd):只读运动、只写动画
## ├─ CameraRig (Node3D) ← 承担偏航 yaw,独立于本体旋转
## │ └─ SpringArm (SpringArm3D) ← 承担俯仰 pitch,自动避障
## │ └─ Camera (Camera3D)
@@ -20,7 +18,7 @@ extends CharacterBody3D
## 滑索:走到缆下按 E 挂上,沿缆滑向低端,缆上按 S 刹车、空格跳离。
## 手感参数(速度/刹车/吸附半径)全在 Zipline 组件上,本文件只读不定义 —— 见文件末尾。
##
## 操作:WASD/方向键移动,鼠标转视角,Shift 疾跑,空格跳跃,E 滑索,Esc 释放/锁定鼠标
## 操作:WASD/方向键移动,鼠标转视角,Shift 疾跑,Ctrl 蹲下(蹲着走即潜行),空格跳跃,E 滑索,Esc 释放/锁定鼠标
## 跳跃输入缓冲帧数(输入事件在渲染帧到达,物理帧读取,避免漏跳)
const JUMP_BUFFER_FRAMES: int = 6
@@ -62,8 +60,8 @@ const JUMP_BUFFER_FRAMES: int = 6
## 滑索操作提示,同样在 player.tscn 里配好,默认隐藏
@onready var _hint: Label3D = $InteractHint
## 动画状态机(挂在 Body 下)。只把「运动结果」交给它,也只知道它会自己播动画。
@onready var animator: PlayerAnimator = $Body/PlayerAnimator
## 动画状态机(挂在 Body/AnimationPlayer 上)。只把「运动结果」交给它,也只知道它会自己播动画。
@onready var animator: PlayerAnimator = $Body/AnimationPlayer
var _gravity: float = float(ProjectSettings.get_setting("physics/3d/default_gravity", 9.8))
var _yaw: float = 0.0
@@ -197,7 +195,12 @@ func _physics_process(delta: float) -> void:
move_and_slide()
# 动画只读运动结果。控制器不认识任何片段名,动画器也不认识输入。
animator.set_motion(velocity, is_on_floor(), Input.is_action_pressed("sprint"))
animator.set_motion(
velocity,
is_on_floor(),
Input.is_action_pressed("sprint"),
Input.is_action_pressed("crouch"),
)
# ---------------- 滑索 ----------------
@@ -256,10 +259,10 @@ func _detach_zipline(hop: bool = false) -> void:
## 让物理引擎去推反而会和「贴着曲线走」这个硬约束打架。
## velocity 仍然维护 —— 一是给动画器读,二是脱手后能带着惯性飞出去。
func _ride_zipline(delta: float) -> void:
var tan := _zipline.tangent(_zip_t) * float(_zip_dir)
var tan_dir := _zipline.tangent(_zip_t) * float(_zip_dir)
# 重力沿缆方向的分量:缆越陡加速越猛,平缆上几乎不加速。
# 下坡时 tan.y 是负的,所以前面要加负号。
_zip_speed += -_gravity * _zipline.gravity_scale * tan.y * delta
# 下坡时 tan_dir.y 是负的,所以前面要加负号。
_zip_speed += -_gravity * _zipline.gravity_scale * tan_dir.y * delta
if Input.is_action_pressed("move_back"):
_zip_speed -= _zipline.brake_accel * delta
_zip_speed = clampf(_zip_speed, 0.0, _zipline.max_speed)
@@ -276,8 +279,8 @@ func _ride_zipline(delta: float) -> void:
_zip_t = next_t
_zip_grab_offset = _zip_grab_offset.lerp(Vector3.ZERO, clampf(delta / 0.12, 0.0, 1.0))
global_position = _zipline.ride_point(_zip_t) + _zip_grab_offset
velocity = tan * _zip_speed
var travel_yaw := atan2(-tan.x, -tan.z)
velocity = tan_dir * _zip_speed
var travel_yaw := atan2(-tan_dir.x, -tan_dir.z)
body.rotation.y = lerp_angle(body.rotation.y, travel_yaw, clampf(turn_speed * delta, 0.0, 1.0))
# 相机也跟着摆到行进方向背后 —— 否则人是横着飞的,看不见前面要去哪。
# 速率刻意比转身慢:玩家用鼠标看的视角不会被立刻拽回去。
+1 -7
View File
@@ -37,7 +37,7 @@ fov = 82.2
[node name="Body" type="Node3D" parent="." unique_id=394283421]
[node name="mouse" parent="Body" unique_id=1995806863 instance=ExtResource("2_wu8e1")]
transform = Transform3D(0.18240133, 0, 0, 0, 0.18240133, 0, 0, 0, 0.18240133, 0, 0.8705118, 0)
transform = Transform3D(-0.18240134, 0, -1.5946032e-08, 0, 0.18240134, 0, 1.5946032e-08, 0, -0.18240134, 0, 0.8705118, 0)
[node name="AnimationPlayer" type="AnimationPlayer" parent="Body" unique_id=1656879850]
root_node = NodePath("../mouse")
@@ -49,12 +49,6 @@ libraries/run = ExtResource("7_muf2e")
libraries/sneak = ExtResource("8_jo6ux")
libraries/walk = ExtResource("9_fkbv7")
script = ExtResource("3_g20gq")
blend_time = null
idle_threshold = null
speed_scale_min = null
speed_scale_max = null
walk_ref_speed = null
sprint_ref_speed = null
[node name="Sync" type="MultiplayerSynchronizer" parent="." unique_id=1979575210]
replication_config = ExtResource("3_wu8e1")
+81 -24
View File
@@ -1,23 +1,36 @@
class_name PlayerAnimator
extends Node
## 玩家表现层:把「运动结果」翻译成动画片段 —— 只读运动、只写动画,不碰物理。
##
## 控制器每物理帧调一次 set_motion(),本节点据此决定 AnimState 并切片段。
## 片段名集中在 ANIM_CLIPS,换模型 / 加动作只改这张表,控制器不认识任何片段名。
##
## 节点接法:本脚本直接挂在 Body/AnimationPlayer 上 —— 这时 animation_player 留空,
## _ready() 会在父节点的子节点里找 AnimationPlayer,找到的就是它自己。
## 以后想把表现层拆成独立节点也行:挂到一个普通 Node 上、用 animation_player 指过去即可,代码不用改。
enum AnimState { IDLE, WALK, CROUCH, RUN, FALL, SNEAK, JUMP }
## 状态 → 片段名。这里写短名就行,_ready() 会把它们解析成 AnimationPlayer 里真正的键。
const ANIM_CLIPS: Dictionary = {
AnimState.IDLE: "idle",
AnimState.WALK: "walk",
AnimState.CROUCH: "crouch",
AnimState.RUN: "run",
AnimState.SNEAK: "SNEAK",
AnimState.SNEAK: "sneak",
AnimState.JUMP: "jump",
AnimState.FALL: "fall",
}
## 需要循环的状态。
const ANIM_LOOPED: Array[int] = [AnimState.IDLE, AnimState.WALK, AnimState.RUN]
## 需要循环的状态。其余(jump / fall)播完停在最后一帧。
## crouch / sneak 也是循环的位移动作 —— 漏掉它们,蹲着走一步就会定住。
const ANIM_LOOPED: Array[int] = [
AnimState.IDLE, AnimState.WALK, AnimState.CROUCH, AnimState.RUN, AnimState.SNEAK
]
@export_group("接线")
## 要驱动的 AnimationPlayer。留空则在本节点的兄弟子树里自动找一个。
## 换模型后这里重新指一下即可 —— 这也是它能脱离具体模型的原因。
## 要驱动的 AnimationPlayer。留空则自动找:脚本挂在 AnimationPlayer 上时就是它自己,
## 挂到独立节点上时是父节点下的第一个。换模型后重指一下即可 —— 这也是它能脱离具体模型的原因。
@export var animation_player: AnimationPlayer
@export_group("播放")
@@ -31,11 +44,16 @@ const ANIM_LOOPED: Array[int] = [AnimState.IDLE, AnimState.WALK, AnimState.RUN]
@export var speed_scale_max: float = 1.6
@export_group("片段基准速度")
## walk 片段在多少米/秒下按 1.0 倍播放。这是片段自身的属性,不是控制器的手感参数:
## 控制器把跑速调到 6 m/s 时,这段动画自然播成 1.2 倍,脚步自动跟上,无需同步改两边。
## 各片段在多少米/秒下按 1.0 倍播放。这是片段自身的属性,不是控制器的手感参数:
## 控制器把跑速调到 6 m/s 时,这段动画自然播成 1.2 倍,脚步自动跟上,两边不用对齐。
@export var walk_ref_speed: float = 5.0
## sprint 片段的基准速度(米/秒)
@export var sprint_ref_speed: float = 8.5
@export var run_ref_speed: float = 8.5
@export var crouch_ref_speed: float = 2.5
@export var sneak_ref_speed: float = 1.6
## 状态 → AnimationPlayer 里真正的片段键(形如 "walk/walk")。_ready() 里解析一次。
## 不直接拿 ANIM_CLIPS 的值去播,是因为多库时短名查不到 —— 见 _ready() 里的说明。
var _clips: Dictionary = {}
## 当前动作状态(AnimState)。权威端每物理帧写一次,Sync 复制给远端。
var anim_state: int = AnimState.IDLE:
@@ -43,7 +61,7 @@ var anim_state: int = AnimState.IDLE:
if anim_state == value:
return
anim_state = value
_play(ANIM_CLIPS.get(anim_state, ""), blend_time)
_play(str(_clips.get(anim_state, "")), blend_time)
## 当前播放倍率(1.0 = 片段原速)。
## 同样要复制:远端只有 position,算不出真实速度,只能照抄权威端的倍率。
@@ -56,21 +74,48 @@ var anim_speed: float = 1.0:
func _ready() -> void:
if animation_player == null and get_parent() != null:
# 脚本就挂在 AnimationPlayer 上,所以这里「在父节点的子节点里找」找到的其实是它自己;
# 表现层哪天拆成独立节点,这段也不用改 —— 找到的就是真正的播放器。
# (不能写成 self as AnimationPlayer:加了 class_name 之后 self 的静态类型是本脚本,转不过去。)
for sibling in get_parent().get_children():
if sibling is AnimationPlayer:
animation_player = sibling as AnimationPlayer
break
if animation_player == null:
push_warning("%s 没绑定 AnimationPlayer,角色不会有动画" % get_path())
return
# 片段在 AnimationPlayer 里的键是「库名/片段名」—— 导入时每个 glb 各自成一个库,
# 短名 has_animation() / get_animation() 一律查不到(实测:has_animation("idle") 为假,
# has_animation("idle/idle") 才为真)。所以这里扫一遍库,把状态对应的真键找出来;
# 缺片段直接点名,免得又变成「名字看着对、播出来没反应」的静默失效。
for state in ANIM_CLIPS:
var clip: String = ANIM_CLIPS[state]
for lib_name in animation_player.get_animation_library_list():
var lib := animation_player.get_animation_library(lib_name)
if lib != null and lib.has_animation(clip):
_clips[state] = clip if String(lib_name).is_empty() else "%s/%s" % [lib_name, clip]
break
if not _clips.has(state):
push_warning("PlayerAnimator 找不到片段「%s」,对应状态不会有动画" % clip)
_patch_loop_modes()
# 同步可能在 _ready() 之前就把 anim_state 写进来了 —— 那时 animation_player 还是 null,
# setter 空跑了一趟。所以这里按「当前状态」补播一遍,不能写死 idle。
_play(ANIM_CLIPS.get(anim_state, ""), 0.0)
_play(str(_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)
## crouching 就是「按住了蹲键」这个输入事实;蹲着不动算 CROUCH、蹲着走算 SNEAK,
## 这个区分在这里做,控制器不需要知道两个状态有什么不一样。不传就是普通站立。
func set_motion(
velocity: Vector3, on_floor: bool, sprinting: bool = false, crouching: bool = false
) -> void:
var state := _resolve_state(velocity, on_floor, sprinting, crouching)
# 先写倍率再切片段 —— 顺序反了会让新片段用一帧旧倍率。
anim_speed = _speed_scale_for(state, velocity)
anim_state = state # setter 负责切片段
@@ -85,25 +130,38 @@ func current_clip() -> String:
# ---------------- 内部 ----------------
func _resolve_state(velocity: Vector3, on_floor: bool, sprinting: bool) -> int:
## 优先级:空中 > 蹲 > 移动。
## 空中最优先 —— 跳 / 落时不关心脚下是走还是蹲。
## 蹲排在移动前面:只要按着蹲键就播蹲的片段,不会因为没动就弹回站立。
## 蹲着不动是 CROUCH(原地蹲),蹲着走是 SNEAK(潜行)—— 两者只差「有没有在移动」。
func _resolve_state(
velocity: Vector3, on_floor: bool, sprinting: bool, crouching: 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:
var moving := Vector2(velocity.x, velocity.z).length() >= idle_threshold
if crouching:
return AnimState.SNEAK if moving else AnimState.CROUCH
if not moving:
return AnimState.IDLE
return AnimState.SPRINT if sprinting else AnimState.WALK
return AnimState.RUN 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
AnimState.RUN:
ref = run_ref_speed
AnimState.CROUCH:
ref = crouch_ref_speed
AnimState.SNEAK:
ref = sneak_ref_speed
_:
return 1.0
if ref <= 0.0:
@@ -114,15 +172,14 @@ func _speed_scale_for(state: int, velocity: Vector3) -> float:
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)
func _patch_loop_modes() -> void:
# 导入的 GLB 片段 loop_mode 默认是 NONE,播一遍就定在最后一帧;
# 这是导入产物的属性,编辑器里改不了,只能在运行时补。
for state in ANIM_LOOPED:
var clip: String = ANIM_CLIPS[state]
if not animation_player.has_animation(clip):
var clip: String = _clips.get(state, "")
if clip.is_empty():
continue
animation_player.get_animation(clip).loop_mode = Animation.LOOP_LINEAR
+2 -2
View File
@@ -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("Body/PlayerAnimator:anim_state")
properties/3/path = NodePath("Body/AnimationPlayer:anim_state")
properties/3/spawn = true
properties/3/replication_mode = 1
properties/4/path = NodePath("Body/PlayerAnimator:anim_speed")
properties/4/path = NodePath("Body/AnimationPlayer:anim_speed")
properties/4/spawn = true
properties/4/replication_mode = 1