C # gravity simulator acting weird

I am working on simulating gravity using C # and Winforms, and I am getting very strange behavior. This pretty much makes the object when you click, and attracted to other objects. The problem is that if they are not within some strange distances, they will not be attracted in positive directions (right, down), but they will be attracted up and to the left.

This is the update code:

public Vector GetGravEffect(GravObject other) { if ((Math.Abs(X - other.X) <= Mass * Form.DrawScale + other.Mass * Form.DrawScale) && (Math.Abs(Y - other.Y) <= Mass * Form.DrawScale + other.Mass * Form.DrawScale)) { return new Vector(0, 0); } double tAngle = Math.Atan2((other.Y - Y), (other.X - X)); double tMagnitude = (GravModifier * Mass * other.Mass / ((Math.Pow((other.X - X), 2)) + (Math.Pow((other.Y - Y), 2))) * 1000); Complex c = Complex.FromPolarCoordinates(tMagnitude, tAngle); Vector r = new Vector(c.Real, c.Imaginary); return r; } 

Full code is here: https://docs.google.com/open?id=0B79vmyWxBr-kTnUtQURPUlVidzQ

Thanks for any help!

+4
source share
1 answer

The problem is not with the GetGravEffect method (it gives the correct results), but with the update method. He completely ignores physical laws. You cannot summarize the values ​​returned by GetGravEffect and take it as speed. GetGravEffect returns the strength that one object attracts another. You must summarize these forces, and then perform additional calculations, which include inertia, acceleration and time to calculate the resulting speed. Also, distinguishing between X and Y from int is not very good, because you lose most of the accuracy, especially for slow speeds. Using the following fixed method, it works fine:

  public void Update() { Vector Force = new Vector(0, 0); foreach (GravObject g in Form.Objects) { if (this != g) Force += GetGravEffect(g); } double TimeElapsedSinceLastUpdate = Form.Timer.Interval * 0.001; Vector acceleration = Force / Mass; Velocity += acceleration*TimeElapsedSinceLastUpdate; X = (X + Velocity.X * Form.VelocityScale); Y = (Y + Velocity.Y * Form.VelocityScale); if (X + Mass * Form.DrawScale >= Form.Panels.Panel2.Width || X - Mass * Form.DrawScale <= 0) Velocity.X *= -1; if (Y + Mass * Form.DrawScale >= Form.Panels.Panel2.Height || Y - Mass * Form.DrawScale <= 0) Velocity.Y *= -1; } 
+5
source

Source: https://habr.com/ru/post/1413361/


All Articles