particles/Main.cs

69 lines
2.6 KiB
C#
Raw Normal View History

2021-12-26 14:58:58 -05:00
using Godot;
using Particles.ParticleSimulation;
2021-12-26 14:58:58 -05:00
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
2021-12-26 14:58:58 -05:00
public class Main : Node2D
{
private Node2D _particleNodes;
2021-12-27 14:58:33 -05:00
private ParticleSimulation _particleSimulation;
public float PhysicsInterpolationFraction;
2021-12-26 14:58:58 -05:00
public override void _Ready()
{
2021-12-29 15:08:26 -05:00
_particleNodes = GetNode<Node2D>("ParticleNodes");
2021-12-26 15:56:57 -05:00
GD.Randomize();
2021-12-29 15:08:26 -05:00
ulong randomSeed = GD.Randi();
GD.Seed(randomSeed);
GD.Print("Last Seed: " + randomSeed);
2021-12-29 15:08:26 -05:00
var viewSize = GetViewportRect().Size;
var zoom = GetNode<Camera2D>("Camera2D").Zoom;
var spaceSize = new Vector2(viewSize.x * zoom.x, viewSize.y * zoom.y);
_particleSimulation = new ParticleSimulation
{
2021-12-29 15:08:26 -05:00
SpaceSize = spaceSize
};
_particleSimulation.Initialize();
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
2021-12-26 14:58:58 -05:00
}
public override void _Process(float delta)
{
2021-12-26 15:56:57 -05:00
if (Input.IsActionJustPressed("quit")) GetTree().Quit();
if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene();
PhysicsInterpolationFraction = Engine.GetPhysicsInterpolationFraction();
2021-12-26 15:56:57 -05:00
}
2021-12-26 21:16:28 -05:00
public override void _PhysicsProcess(float delta)
{
_particleSimulation.Update();
foreach (var id in _particleSimulation.LastParticlesRemoved)
2021-12-26 16:45:02 -05:00
{
var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString());
particleNode.Free();
2021-12-26 16:45:02 -05:00
}
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
2021-12-27 16:10:07 -05:00
var particleNodes = _particleNodes.GetChildren();
foreach (ParticleNode particleNode in particleNodes)
2021-12-26 23:08:40 -05:00
{
var simulationParticle = _particleSimulation.GetParticle(particleNode.SimulationId);
particleNode.LastSimulationPosition = particleNode.Position;
particleNode.CurrentSimulationPosition = simulationParticle.Position;
particleNode.SetColor(simulationParticle.Type.Hue, simulationParticle.Health,
Mathf.Clamp(simulationParticle.AverageSpeed / 1.5f, 1f, 1f));
2021-12-29 15:08:26 -05:00
particleNode.WasTeleportedLast = simulationParticle.WasTeleportedLast;
2021-12-26 23:08:40 -05:00
}
2021-12-27 16:10:07 -05:00
}
private void CreateParticleNode(int id)
2021-12-27 16:10:07 -05:00
{
var particleScene = GD.Load<PackedScene>("res://ParticleNode.tscn");
var particleNode = particleScene.Instance<ParticleNode>();
particleNode.Name = id.ToString();
particleNode.SimulationId = id;
_particleNodes.AddChild(particleNode);
2021-12-26 21:16:28 -05:00
}
2021-12-26 15:56:57 -05:00
}