New player add method

This commit is contained in:
Marco 2025-01-22 11:35:37 +01:00
commit a235183c61
8 changed files with 116 additions and 58 deletions

54
Scripts/GameManager.cs Normal file
View file

@ -0,0 +1,54 @@
using Godot;
using System;
using Cirno.Scripts;
public partial class GameManager : Node2D
{
private Hud _hud;
private PlayerMovement _player;
private Node2D _cameraTarget;
[Export]
public PackedScene PlayerTemplate { get; set; }
[Export]
public Marker2D PlayerSpawnMarker { get; set; }
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
_hud = GetNode<Hud>("HUD");
_cameraTarget = GetNode<Node2D>("CameraTarget");
if (PlayerSpawnMarker != null)
{
SpawnPlayer();
}
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(double delta)
{
}
public void SpawnPlayer()
{
if (_player == null)
{
//_player = this.CreateChild<PlayerMovement>(PlayerTemplate, PlayerSpawnMarker.Position );
_player = PlayerTemplate.Instantiate<PlayerMovement>();
this.CallDeferred("add_child", _player);
_player.Transform = this.GlobalTransform;
_player.GlobalPosition = PlayerSpawnMarker.Position;
_cameraTarget.Reparent(_player, true);
_cameraTarget.GlobalPosition = _player.Position;
}
}
}

View file

@ -37,7 +37,7 @@ public partial class PlayerMovement : CharacterBody2D, IDestructible
[Export] public Weapon EquippedWeapon;
private float _currentHealth = 0f;
private bool _isDestroyed = false;
//private InventoryManager _inventoryManager;

View file

@ -5,6 +5,11 @@ namespace Cirno.Scripts;
public static class Tools
{
public static T CreateChild<T>(this Node2D node, PackedScene prefab) where T : Node2D
{
return CreateChild<T>(node, prefab, node.Position);
}
public static T CreateChild<T>(this Node2D node, PackedScene prefab, Vector2 position) where T : Node2D
{
if (prefab == null) return null;
var newInstance = prefab.Instantiate<T>();
@ -12,7 +17,7 @@ public static class Tools
// Need to use parent instead of owner because tilemap scenes have no owner
//node.Owner.CallDeferred("add_child", newInstance);
newInstance.Transform = node.GlobalTransform;
newInstance.Position = node.Position;
newInstance.Position = position;
return newInstance;
}

View file

@ -73,6 +73,7 @@ public partial class Weapon : Node2D
}
// TODO: Shoot at muzzle position, need to provide a way to turn it, on a radius?
// TODO: Create not as child but as standalone
var bullet = this.CreateChild<Bullet>(BulletScene);
bullet.SetDirection(ShootDirection);
bullet.Speed = BulletSpeed;