3D_RPG_Action_Game/Player/Player.cs

72 lines
2.1 KiB
C#

using DRPGActionGame.Player.States;
using Godot;
using static DRPGActionGame.Player.States.StateFactory.States;
namespace DRPGActionGame.Player;
public partial class Player : CharacterBody3D
{
[Export] private AnimationTree? animationTree;
[Export] private CameraController? cameraController;
[Export] public Node3D? PlayerMesh;
public const float SPEED = 5.0f;
public const float JUMP_VELOCITY = 10f;
public Vector3 Direction;
public AnimationNodeStateMachinePlayback? Playback;
private State? state;
private float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
public override void _Ready() {
if (animationTree != null) {
Playback = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/playback");
animationTree.AnimationFinished += OnAnimationFinished;
}
else {
GD.PrintErr("No AnimationTree defined!");
}
ChangeState(Idle);
}
private void OnAnimationFinished(StringName animationName) {
if (animationName == "1H_Melee_Attack_Chop")
ChangeState(Direction == Vector3.Zero ? Idle : Move);
// else if (animationName == "Jump_Full_Long")
// ChangeState(Direction == Vector3.Zero ? Idle : Move);
}
public override void _PhysicsProcess(double delta)
{
Vector3 velocity = Velocity;
if (!IsOnFloor()) velocity.Y -= gravity * (float)delta;
Direction = new(Input.GetActionStrength("WalkLeft") - Input.GetActionStrength("WalkRight"), 0, Input.GetActionStrength("WalkUp") - Input.GetActionStrength("WalkDown"));
if (cameraController != null) {
float hRot = cameraController.Transform.Basis.GetEuler().Y;
Direction = Direction.Rotated(Vector3.Up, hRot).Normalized();
}
else {
GD.PrintErr("No CameraController defined!");
}
Velocity = velocity;
MoveAndSlide();
}
public void ChangeState(StateFactory.States newState) {
//Remove state if available
state?.ExitState();
//Add New State
state = new StateFactory().GetState(newState);
if (state != null) {
state.Setup(newState, Playback, this);
state.Name = newState.ToString();
AddChild(state);
}
else {
GD.PrintErr($"State {newState} not found!");
}
}
}