carotrauma/scenes/sandbox/player/SandboxPlayer.cs
Nick Guy c98d7739aa
All checks were successful
/ build (push) Successful in 1m32s
Add custom input mapping on top of Godot's InputMap
2024-06-02 17:10:15 +01:00

92 lines
No EOL
2.5 KiB
C#

using System.Collections.Generic;
using Carotrauma.scripts.libs.input;
using Godot;
namespace Carotrauma.scenes.sandbox.player;
public partial class SandboxPlayer : CharacterBody3D, IInputProvider
{
[Export]
public float Speed = 5.0f;
[Export]
public float JumpVelocity = 4.5f;
[Export] public float MouseSensitivity = 0.05f;
// Get the gravity from the project settings to be synced with RigidBody nodes.
public float gravity = ProjectSettings.GetSetting("physics/3d/default_gravity").AsSingle();
private float camera_anglev = 0;
private Node3D pivot;
private Camera3D cam;
private KeyInputAction GrabCursor;
private KeyInputAction Jump;
private VectorInputAction Movement;
public void CreateInputs() {
GrabCursor = this.KeyInput(Key.Escape);
Jump = this.KeyInput(Key.Space);
Movement = this.VectorKeyInput(Key.D, Key.A, Key.S, Key.W);
}
public override void _EnterTree() {
CreateInputs();
}
public override void _Ready() {
pivot = GetChild<Node3D>(2, true);
cam = pivot.GetChild<Camera3D>(0, true);
}
public override void _Input(InputEvent @event) {
if (@event is InputEventMouseMotion && Input.MouseMode == Input.MouseModeEnum.Captured) {
var M = (InputEventMouseMotion)@event;
pivot.RotateX(Mathf.DegToRad(-M.Relative.Y * MouseSensitivity));
RotateY(Mathf.DegToRad(-M.Relative.X * MouseSensitivity));
Vector3 cameraRot = pivot.RotationDegrees;
cameraRot.X = Mathf.Clamp(cameraRot.X, -70, 70);
pivot.RotationDegrees = cameraRot;
}
}
public override void _PhysicsProcess(double delta) {
if (GrabCursor.IsJustPressed())
Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Visible ? Input.MouseModeEnum.Captured : Input.MouseModeEnum.Visible;
Vector3 velocity = Velocity;
// Add the gravity.
if (!IsOnFloor())
velocity.Y -= gravity * (float)delta;
// Handle Jump.
if (Jump.IsJustPressed() && 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 = Movement.GetStrength();
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;
}
else
{
velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
velocity.Z = Mathf.MoveToward(Velocity.Z, 0, Speed);
}
Velocity = velocity;
MoveAndSlide();
}
public List<InputAction> Actions => _actions;
private List<InputAction> _actions = new();
}