cirnogodot/Scripts/PlayerMovement.cs
2024-05-01 12:49:46 +02:00

108 lines
2 KiB
C#

using Godot;
using System;
using System.Diagnostics;
public partial class PlayerMovement : CharacterBody2D
{
[Export]
public int Speed { get; set; } = 400;
[Export]
public PackedScene BulletScene { get; set; }
[Export]
public Marker2D Muzzle { get; set; }
private AnimatedSprite2D _animatedSprite;
private Vector2 _movementDirection { get; set; }
private Vector2 _facingDirection { get; set; }
public override void _Ready()
{
_animatedSprite = GetNode<AnimatedSprite2D>("./Smoothing2D/AnimatedSprite2D");
_movementDirection = Vector2.Zero;
_facingDirection = Vector2.Zero;
}
/*public override _Process(float _delta)
{
if (Input.IsActionPressed("ui_right"))
{
_animatedSprite.Play("run");
}
else
{
_animatedSprite.Stop();
}
}*/
public override void _Process(double delta)
{
HandleShoot();
SetAnimation();
}
private void HandleShoot()
{
if (Input.IsActionJustPressed("shoot"))
{
Debug.WriteLine("Shoot");
Bullet bullet = BulletScene.Instantiate<Bullet>();
Owner.AddChild(bullet);
bullet.Transform = Muzzle.GlobalTransform;
bullet.Position = this.Position;
bullet.SetDirection(this._movementDirection);
}
}
private void SetAnimation()
{
if (Velocity.X == 0 && Velocity.Y == 0)
{
_animatedSprite.SpeedScale = 0;
}
else
{
_animatedSprite.SpeedScale = 1;
}
if (Velocity.X > 0)
{
_animatedSprite.Play("walk_right");
}
else if (Velocity.X < 0)
{
_animatedSprite.Play("walk_left");
}
else if (Velocity.Y > 0)
{
_animatedSprite.Play("walk_down");
}
else if (Velocity.Y < 0)
{
_animatedSprite.Play("walk_up");
}
}
public Vector2 GetInput()
{
return Input.GetVector("left", "right", "up", "down");
}
public override void _PhysicsProcess(double delta)
{
_movementDirection = GetInput();
if (_movementDirection != Vector2.Zero) {
_facingDirection = _movementDirection;
}
Velocity = _movementDirection * (float)(Speed * delta);
MoveAndSlide();
}
}