harvest/game/scripts/player_character.gd
2026-10-03 12:14:28 -04:00

54 lines
2.1 KiB
GDScript

class_name PlayerCharacter
extends CharacterBody3D
## The farmer: camera-relative movement on the move_* actions (WASD / arrows / left stick) with
## gravity. The model turns toward the direction of travel and crossfades idle / walk / run.
## The walk clip plays for partial stick deflection; full keyboard input runs.
@export var run_speed := 5.0
@export var acceleration := 30.0
## How quickly the model turns to face the movement direction (higher = snappier).
@export var turn_speed := 12.0
## Input strength (0..1) above which the run clip plays instead of the walk clip.
@export_range(0.0, 1.0) var run_threshold := 0.6
@export_group("Animation")
@export var idle_animation: StringName = &"Idle_A"
@export var walk_animation: StringName = &"Walking_A"
@export var run_animation: StringName = &"Running_A"
@export var blend_time := 0.2
@onready var model: Node3D = $Model
@onready var animation_player: AnimationPlayer = $Model/AnimationPlayer
func _physics_process(delta: float) -> void:
var move := _move_direction()
var horizontal := Vector3(velocity.x, 0.0, velocity.z).move_toward(move * run_speed, acceleration * delta)
velocity.x = horizontal.x
velocity.z = horizontal.z
if not is_on_floor():
velocity += get_gravity() * delta
move_and_slide()
if move.length_squared() > 1e-4:
var yaw := atan2(-move.x, -move.z)
model.rotation.y = lerp_angle(model.rotation.y, yaw, 1.0 - exp(-turn_speed * delta))
_update_animation(move.length())
## Input rotated by the active camera's yaw, so "forward" is always up the screen.
func _move_direction() -> Vector3:
var input := Input.get_vector("move_left", "move_right", "move_forward", "move_back")
var camera := get_viewport().get_camera_3d()
var yaw := camera.global_rotation.y if camera != null else 0.0
return Vector3(input.x, 0.0, input.y).rotated(Vector3.UP, yaw)
func _update_animation(strength: float) -> void:
var clip := idle_animation
if strength > run_threshold:
clip = run_animation
elif strength > 0.0:
clip = walk_animation
if animation_player.current_animation != clip:
animation_player.play(clip, blend_time)