particles/ParticleSimulation/ParticleSimulationScene.cs

68 lines
2.6 KiB
C#
Raw Normal View History

2022-01-17 23:52:42 -05:00
using Godot;
using Particles.ParticleSimulation;
// ReSharper disable once CheckNamespace
// ReSharper disable once ClassNeverInstantiated.Global
public class ParticleSimulationScene : Node2D
{
private Node2D _particleNodes;
private ParticleSimulation _particleSimulation;
public float PhysicsInterpolationFraction;
2022-01-25 12:02:24 -05:00
public void Initialize(int seed, int nParticles)
2022-01-17 23:52:42 -05:00
{
_particleNodes = GetNode<Node2D>("ParticleNodes");
2022-01-25 12:02:24 -05:00
GD.Seed((ulong)seed);
GD.Print("Last Seed: " + seed);
2022-01-17 23:52:42 -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
{
SpaceSize = spaceSize
};
_particleSimulation.Initialize(nParticles);
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
}
public override void _Process(float delta)
{
2022-01-25 12:02:24 -05:00
if (Input.IsActionJustPressed("quit"))
GetParent<Main>().ExitToMenu();
2022-01-17 23:52:42 -05:00
if (Input.IsActionJustPressed("reset")) GetTree().ReloadCurrentScene();
PhysicsInterpolationFraction = Engine.GetPhysicsInterpolationFraction();
}
public override void _PhysicsProcess(float delta)
{
_particleSimulation.Update();
foreach (var id in _particleSimulation.LastParticlesRemoved)
{
var particleNode = _particleNodes.GetNode<ParticleNode>(id.ToString());
particleNode.Free();
}
foreach (var id in _particleSimulation.LastParticlesAdded) CreateParticleNode(id);
var particleNodes = _particleNodes.GetChildren();
foreach (ParticleNode particleNode in particleNodes)
{
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));
particleNode.WasTeleportedLast = simulationParticle.WasTeleportedLast;
}
}
private void CreateParticleNode(int id)
{
2022-01-18 12:01:37 -05:00
var particleScene = GD.Load<PackedScene>("res://ParticleSimulation/ParticleNode.tscn");
2022-01-17 23:52:42 -05:00
var particleNode = particleScene.Instance<ParticleNode>();
particleNode.Name = id.ToString();
particleNode.SimulationId = id;
_particleNodes.AddChild(particleNode);
}
}