Skip to content

Instantly share code, notes, and snippets.

@rekyuu
Last active May 2, 2022 23:24
Show Gist options
  • Save rekyuu/90a6b95be663952e15d29caa760b102b to your computer and use it in GitHub Desktop.
Save rekyuu/90a6b95be663952e15d29caa760b102b to your computer and use it in GitHub Desktop.
Godot 3 Scripts
using Godot;
public class Player : KinematicBody
{
[Export] public float Speed = 7.0f;
[Export] public float JumpStrength = 20.0f;
[Export] public float Gravity = 50.0f;
private Vector3 _velocity = Vector3.Zero;
private Vector3 _snapVector = Vector3.Down;
private SpringArm _springArm;
private Spatial _model;
public override void _Ready()
{
_springArm = GetNode<SpringArm>("SpringArm");
_model = GetNode<Spatial>("Model");
}
public override void _Process(float delta)
{
_springArm.Translation = Translation;
}
public override void _PhysicsProcess(float delta)
{
Vector3 moveDir = Vector3.Zero;
moveDir.x = Input.GetActionStrength("right") - Input.GetActionStrength("left");
moveDir.z = Input.GetActionStrength("back") - Input.GetActionStrength("forward");
moveDir = moveDir.Rotated(Vector3.Up, _springArm.Rotation.y).Normalized();
_velocity.x = moveDir.x * Speed;
_velocity.z = moveDir.z * Speed;
_velocity.y -= Gravity * delta;
bool justLanded = IsOnFloor() && _snapVector == Vector3.Zero;
bool isJumping = IsOnFloor() && Input.IsActionJustPressed("jump");
if (isJumping)
{
_velocity.y = JumpStrength;
_snapVector = Vector3.Zero;
}
else if (justLanded)
{
_snapVector = Vector3.Down;
}
_velocity = MoveAndSlideWithSnap(_velocity, _snapVector, Vector3.Up, true);
if (_velocity.Length() >= 0.2f)
{
Vector3 modelRotation = _model.Rotation;
Vector2 lookDir = new Vector2(_velocity.z, _velocity.x);
modelRotation.y = lookDir.Angle();
_model.Rotation = modelRotation;
}
}
}
using Godot;
using System;
public class SpringArm : Spatial
{
[Export] public float MouseSensitivity = 0.05f;
public override void _Ready()
{
SetAsToplevel(true);
Input.SetMouseMode(Input.MouseMode.Captured);
}
public override void _UnhandledInput(InputEvent @event)
{
if (@event is InputEventMouseMotion mouseEvent)
{
Vector3 rotation = RotationDegrees;
rotation.x -= mouseEvent.Relative.y * MouseSensitivity;
rotation.x = Mathf.Clamp(rotation.x, -90.0f, 30.0f);
rotation.y -= mouseEvent.Relative.x * MouseSensitivity;
rotation.y = Mathf.Wrap(rotation.y, -0.0f, 360.0f);
RotationDegrees = rotation;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment