SupaLidlGame/Utils/Spawner.cs

60 lines
1.4 KiB
C#
Raw Normal View History

2023-05-28 10:57:23 -07:00
using Godot;
using Godot.Collections;
2023-06-13 02:55:30 -07:00
using GodotUtilities;
2023-05-28 10:57:23 -07:00
using SupaLidlGame.Extensions;
2023-06-03 18:21:46 -07:00
namespace SupaLidlGame.Utils;
public partial class Spawner : Node2D
2023-05-28 10:57:23 -07:00
{
2023-06-03 18:21:46 -07:00
[Export]
public Area2D SpawnArea { get; set; }
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
[Export]
public PackedScene Character { get; set; }
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
[Export]
public double SpawnTime { get; set; }
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
protected double _timeLeftToSpawn = 0;
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
public override void _Ready()
{
}
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
public override void _Process(double delta)
{
if ((_timeLeftToSpawn -= delta) <= 0)
2023-05-28 10:57:23 -07:00
{
2023-06-03 18:21:46 -07:00
_timeLeftToSpawn = SpawnTime;
Spawn();
2023-05-28 10:57:23 -07:00
}
2023-06-03 18:21:46 -07:00
}
2023-05-28 10:57:23 -07:00
2023-06-03 18:21:46 -07:00
public void Spawn()
{
var coll = GetNode<CollisionShape2D>("Area2D/CollisionShape2D");
var rect = coll.Shape as RectangleShape2D;
if (rect is not null)
2023-05-28 10:57:23 -07:00
{
2023-06-03 18:21:46 -07:00
Vector2 size = rect.Size / 2;
Vector2 pos = GlobalPosition;
double x1, x2, y1, y2;
x1 = pos.X - size.X;
x2 = pos.X + size.X;
y1 = pos.Y - size.Y;
y2 = pos.Y + size.Y;
float randX = (float)GD.RandRange(x1, x2);
float randY = (float)GD.RandRange(y1, y2);
Vector2 randPos = new Vector2(randX, randY);
var chr = Character.Instantiate<Characters.Character>();
chr.GlobalPosition = randPos;
2024-06-06 09:21:39 -07:00
World.Instance.CurrentMap.Entities.AddChild(chr);
2023-05-28 10:57:23 -07:00
}
}
}