From ddb50b0b66c838bc97e79c826ff5375e15f8f038 Mon Sep 17 00:00:00 2001 From: alex Date: Tue, 21 Jul 2026 01:42:31 +0200 Subject: init --- Player.cs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Player.cs (limited to 'Player.cs') diff --git a/Player.cs b/Player.cs new file mode 100644 index 0000000..8a5f5d4 --- /dev/null +++ b/Player.cs @@ -0,0 +1,59 @@ +using Godot; + +public partial class Player : CharacterBody2D +{ + [Export] public float Speed { get; set; } = 300.0f; + [Export] public PackedScene BulletScene { get; set; } + + // Create a reference for your Sprite + private Sprite2D _sprite; + + public override void _Ready() + { + // Grab the Sprite2D node when the game starts + _sprite = GetNode("Sprite2D"); + } + + public override void _PhysicsProcess(double delta) + { + Vector2 direction = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down"); + Velocity = direction * Speed; + MoveAndSlide(); + } + + public override void _Process(double delta) + { + // Get the mouse position + Vector2 mousePos = GetGlobalMousePosition(); + + // If the mouse is to the left of the player, flip the sprite. + // If it's to the right, keep it un-flipped. + _sprite.FlipH = mousePos.X < GlobalPosition.X; + + if (Input.IsActionJustPressed("shoot")) + { + Shoot(); + } + } + private void Shoot() + { + // Failsafe in case you forgot to assign the scene in the editor + if (BulletScene == null) return; + + // Create an instance of the bullet + Bullet bullet = (Bullet)BulletScene.Instantiate(); + + // Spawn it at the player's current position + bullet.GlobalPosition = GlobalPosition; + + // Calculate the direction from the player to the mouse + Vector2 mousePos = GetGlobalMousePosition(); + bullet.Direction = GlobalPosition.DirectionTo(mousePos); + + // Rotate the bullet to face the direction it's traveling + bullet.Rotation = bullet.Direction.Angle(); + + // Add the bullet to the current scene tree so it actually exists in the game + GetTree().Root.AddChild(bullet); + } +} \ No newline at end of file -- cgit v1.2.3