particles/Main.cs
2021-12-26 16:45:02 -05:00

59 lines
1.7 KiB
C#

using System.Collections.Generic;
using Godot;
public class Main : Node2D
{
private readonly List<ParticleType> _particleTypes = new List<ParticleType>();
public override void _Ready()
{
GD.Randomize();
InitializeParticleTypes(5);
InitializeParticles(50);
}
public override void _Process(float delta)
{
if (Input.IsActionJustPressed("quit")) GetTree().Quit();
if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene();
}
private void InitializeParticleTypes(int nTypes)
{
for (var i = 0; i < nTypes; i++)
{
var type = new ParticleType
{
Hue = (float) GD.RandRange(0, 1)
};
_particleTypes.Add(type);
}
}
private void InitializeParticles(int nParticles)
{
var typeCount = 0;
var particleScene = GD.Load<PackedScene>("res://Particle.tscn");
for (var i = 0; i < nParticles; i++)
{
var particle = particleScene.Instance<Particle>();
GetNode<Node2D>("Particles").AddChild(particle);
particle.Position = GetRandomParticlePosition();
particle.Type = _particleTypes[typeCount];
if (typeCount < _particleTypes.Count - 1)
typeCount++;
else
typeCount = 0;
}
}
private Vector2 GetRandomParticlePosition()
{
const int padding = 32;
var viewportRect = GetViewportRect();
var position = new Vector2((float) GD.RandRange(padding, viewportRect.Size.x - padding),
(float) GD.RandRange(padding, viewportRect.Size.y - padding));
return position;
}
}