Aeo*_*dyn 4 c# simulation gravity
我一直在使用C#和Winforms进行(某种)重力模拟,我得到了一些非常奇怪的行为.当你点击它时,它几乎会成为一个对象,并被其他对象吸引.问题在于,除非它们在一些奇怪的距离内,否则它们不会被吸引到正方向(向右,向下),但是它们被向上和向左吸引.
这是更新代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
完整代码如下:https://docs.google.com/open?id = 0B79vmyWxBr-kTnUtQURPUlVidzQ
谢谢你的帮助!
问题不在GetGravEffect方法中(它给出了正确的结果),但在Update方法中.它完全忽略了物理定律.您不能对GetGravEffect返回的值求和,并将其视为速度.GetGravEffect返回一个对象吸引另一个对象的强制.您必须对这些力进行求和,然后执行其他计算,包括惯性,加速度和时间来计算结果速度.同时将X和Y转换为int也不是一个好主意,因为你失去了很多准确性,特别是对于慢速.使用以下更正的方法,它很有效:
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;
}
Run Code Online (Sandbox Code Playgroud)