1bit-game-jam/scripts/Player.cs

72 lines
1.6 KiB
C#

using Godot;
public partial class Player : CharacterBody2D
{
[Export] public const float Speed = 50.0f;
[Signal]
public delegate void KilledEventHandler();
public bool Alive = true;
public static Player Instance { get; private set; }
protected AnimatedSprite2D Sprite;
public override void _Ready()
{
Instance = this;
Sprite = (AnimatedSprite2D)FindChild("AnimatedSprite2D");
}
public override void _PhysicsProcess(double delta)
{
if (!Alive)
return;
Vector2 velocity = Velocity;
// Get the input direction and handle the movement/deceleration.
// As good practice, you should replace UI actions with custom gameplay actions.
Vector2 direction = Input.GetVector("character_left", "character_right", "character_up", "character_down");
if (direction != Vector2.Zero)
{
velocity.X = direction.X * Speed;
velocity.Y = direction.Y * Speed;
var animationName = "sideways";
if (velocity.Y > 0.001f)
animationName = "down";
else if (velocity.Y < 0.001f)
animationName = "up";
if (velocity.X != 0)
animationName = "sideways";
Sprite.FlipH = velocity.X < 0.001f && animationName == "sideways";
Sprite.Play(animationName);
}
else
{
velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
velocity.Y = Mathf.MoveToward(Velocity.Y, 0, Speed);
Sprite.Stop();
}
Velocity = velocity;
MoveAndSlide();
}
public void Kill(Node2D killer)
{
if (!Alive)
return;
GD.Print($"Killed by {killer.Name}");
Alive = false;
EmitSignal(SignalName.Killed);
DeathScreen.Instance.Killed(killer);
}
}