Files
GodotTutorial/Scripts/Player.cs
2023-07-14 10:23:34 -07:00

63 lines
1.7 KiB
C#

using Godot;
public partial class Player : CharacterBody3D
{
public const float Speed = 5.0f;
public const float JumpVelocity = 4.5f;
[Export]
private float _sensitivityHorizontal = 0.05f;
[Export]
private float _sensitivityVertical = 0.05f;
[Export]
private float _joystickDeadZone = 0.5f;
private Node3D _cameraMount;
private Node3D _pivot;
// Get the _gravity from the project settings to be synced with RigidBody nodes.
public float _gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
public override void _Ready()
{
Input.MouseMode = Input.MouseModeEnum.Captured;
_cameraMount = GetNode<Node3D>("/root/Main/Player/CameraMount");
_pivot = GetNode<Node3D>("/root/Main/Player/Pivot");
}
public override void _UnhandledInput(InputEvent @event)
{
if (Input.IsActionJustPressed("quit"))
GetTree().Quit();
}
public override void _PhysicsProcess(double delta)
{
Vector3 velocity = Velocity;
if (!IsOnFloor())
velocity.Y -= _gravity * (float)delta;
if (Input.IsActionJustPressed("jump") && IsOnFloor())
velocity.Y = JumpVelocity;
Vector2 inputDir = Input.GetVector("right", "left", "back", "forward");
Vector3 direction = (Transform.Basis * new Vector3(inputDir.X, 0, inputDir.Y)).Normalized();
if (direction != Vector3.Zero)
{
velocity.X = direction.X * Speed;
velocity.Z = direction.Z * Speed;
direction = direction.Normalized();
GetNode<Node3D>("Pivot").LookAt(Position + direction, Vector3.Up);
}
else
{
velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
velocity.Z = Mathf.MoveToward(Velocity.Z, 0, Speed);
}
Velocity = velocity;
MoveAndSlide();
}
}