Files
GameJam2023/Player/Base/P1Controls.cs
2023-09-06 03:49:16 -07:00

87 lines
2.4 KiB
C#

using Godot;
public partial class P1Controls : Controls
{
[Export]
private PackedScene _fireProjectile;
[Export]
private PackedScene _altFireProjectile;
[Export]
private float _speed = 3.0f;
public bool CanShoot { get; protected set; }
private GameManager _gameManager;
public override void _Ready()
{
CanShoot = true;
_gameManager = GetTree().Root.GetNode<GameManager>("Main/GameManager");
}
public override void _PhysicsProcess(double delta)
{
Velocity = CalculateCharacterMovement(delta);
MoveAndSlide();
}
public override void _UnhandledInput(InputEvent @event)
{
if (Input.IsActionJustPressed("exit"))
GetTree().Quit();
if (Input.IsActionJustPressed($"p1_fire") && CanShoot)
Fire();
if (Input.IsActionJustPressed($"p1_altfire") && CanShoot)
AltFire();
}
private Vector3 CalculateCharacterMovement(double delta)
{
var velocity = Velocity;
var inputDir = Input.GetVector($"p1_left", $"p1_right", $"p1_up", $"p1_down");
var 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;
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);
}
return velocity;
}
private async void Fire()
{
var projectile = _fireProjectile.Instantiate<Projectile>();
projectile.Position = Position + new Vector3(0f, 1f, 0f);
projectile.ParentCharacter = this;
GetParent().AddChild(projectile);
CanShoot = false;
await ToSignal(GetTree().CreateTimer(projectile.Cooldown), "timeout");
CanShoot = true;
}
private async void AltFire()
{
var projectile = _altFireProjectile.Instantiate<Projectile>();
projectile.Position = Position + new Vector3(0f, 1f, 0f);
projectile.ParentCharacter = this;
GetParent().AddChild(projectile);
CanShoot = false;
await ToSignal(GetTree().CreateTimer(projectile.Cooldown), "timeout");
CanShoot = true;
}
public void OnHit(Node3D node)
{
if (this != null)
_gameManager.CallDeferred(GameManager.MethodName.RemoveCharacter, this);
}
}