solarsystem /SolarSystem/System.cs

Language C# Lines 66
MD5 Hash 575a26118f9fff1eba4fe5f927af9729 Estimated Cost $1,212 (why?)
Repository https://bitbucket.org/efouts/solarsystem View Raw File View Project SPDX
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
        }
    }
}
Back to Top