/SolarSystem/System.cs
C# | 65 lines | 52 code | 13 blank | 0 comment | 2 complexity | 575a26118f9fff1eba4fe5f927af9729 MD5 | raw file
Possible License(s): BSD-3-Clause
- using MathNet.Numerics.LinearAlgebra.Double;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MathNet.Numerics.LinearAlgebra.Generic;
- using MathNet.Numerics;
-
- namespace SolarSystem
- {
- public class System
- {
- private const Int32 X = 0;
- private const Int32 Y = 1;
-
- public IEnumerable<Body> Bodies { get; private set; }
-
- public System(IEnumerable<Body> bodies)
- {
- Bodies = bodies;
- }
-
- public void DoTicks(Double ticks)
- {
- foreach (var body in Bodies)
- DoTicks(body, ticks);
- }
-
- private void DoTicks(Body body, Double ticks)
- {
- var acceleration = GetTotalAccelerationActingOnBody(body);
-
- body.Velocity = body.Velocity.Add(acceleration * ticks);
- body.Position = body.Position.Add(body.Velocity * ticks);
-
- var bodyCircumference = 2 * Math.PI * body.Radius;
- var rotationPercentage = body.RotationVelocity * ticks / bodyCircumference;
- body.Rotation += (360 * rotationPercentage) % 360;
- }
-
- private Vector<Double> GetTotalAccelerationActingOnBody(Body body)
- {
- Vector<Double> totalAcceleration = new DenseVector(new[] { 0d, 0d });
-
- foreach (var otherBody in Bodies)
- if (body != otherBody)
- totalAcceleration = totalAcceleration + GetAccelerationDueToGravity(body, otherBody);
-
- return totalAcceleration;
- }
-
- private Vector<Double> GetAccelerationDueToGravity(Body body, Body otherBody)
- {
- var differenceVector = otherBody.Position.Subtract(body.Position);
- var differenceMagnitude = Math.Sqrt(Math.Pow(differenceVector[X], 2) + Math.Pow(differenceVector[Y], 2));
- var differenceUnit = new DenseVector(new[] { differenceVector[X] / differenceMagnitude, differenceVector[Y] / differenceMagnitude });
-
- var accelerationScalar = Constants.GravitationalConstant * otherBody.Mass / Math.Pow(differenceMagnitude, 2);
- var accelerationVector = differenceUnit * accelerationScalar;
-
- return accelerationVector;
- }
- }
- }