Files
GodotTutorial/Scripts/CharacterBody3D.cs
2023-07-14 08:09:39 -07:00

67 lines
1.9 KiB
C#

using Godot;
public partial class CharacterBody3D : Godot.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/CharacterBody3D/CameraMount");
_pivot = GetNode<Node3D>("/root/Main/CharacterBody3D/Pivot");
}
public override void _UnhandledInput(InputEvent @event)
{
if (Input.IsActionJustPressed("quit"))
GetTree().Quit();
}
public override void _PhysicsProcess(double delta)
{
Vector3 velocity = Velocity;
// Add the gravity.
if (!IsOnFloor())
velocity.Y -= gravity * (float)delta;
// Handle Jump.
if (Input.IsActionJustPressed("jump") && IsOnFloor())
velocity.Y = JumpVelocity;
// Get the input direction and handle the movement/deceleration.
// As good practice, you should replace UI actions with custom gameplay actions.
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();
}
}