在我的n身体模拟中,我大约有1k粒子飞来飞去。我将头寸存储为浮点数。我遇到的一个问题是,每当我运行代码时,当两个粒子彼此非常接近(基本上是相同的位置)时,它们就会被极大地加速。通常,粒子的行为会很平稳。
if((planet.position.x != otherPlanet.position.x && planet.position.y != otherPlanet.position.y) && !otherPlanet.delete)
{
//First we get the x,y and magnitudal distance between the two bodies.
float xDist = (otherPlanet.position.x - planet.position.x);
float yDist = (otherPlanet.position.y - planet.position.y);
float dist = Vector2Math.distance(planet.position, otherPlanet.position);
//Now we compute first the total and then the component forces
//Depending on choice, use r or r^2
float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist));
float forceX = force * xDist/dist;
float forceY = force * yDist/dist;
//Given the component forces, we construct the force vector and apply it to the body.
Vector2 forceVec = new Vector2(forceX, forceY);
planet.force = Vector2Math.add(planet.force, forceVec);
otherPlanet.force = Vector2Math.subtract(otherPlanet.force, forceVec);
}
关于这个主题我什么都没找到,但这是我做错的事情还是我必须实现最大加速度或粒子之间的最小距离?
答案 0 :(得分:1)
模拟世界与现实世界有些不同,为了进行良好的模拟,我们需要添加一些限制。
问题:
当两个粒子真正靠近时,它们会爆炸 以惊人的速度向外移动。
原因
这是简单的重力的原因是相反的 与两个物体之间的距离平方成正比。当两个 身体距离太近,半径(它们之间的距离)变得很小 并且作用在它们上面的力变得非常大。
解决方案
为两个粒子可以达到的近距离添加虚拟限制。 虚拟限制,我的意思是限制仅在值上,而不在 模拟。例如如果它们之间的距离小于5(a 阈值),将距离设置为5。
您的代码更改
if((planet.position.x != otherPlanet.position.x && planet.position.y != otherPlanet.position.y) && !otherPlanet.delete)
{
//First we get the x,y and magnitudal distance between the two bodies.
float xDist = (otherPlanet.position.x - planet.position.x);
float yDist = (otherPlanet.position.y - planet.position.y);
// add a limit to xDist and yDist
if(xDist<5)
xDist=5;
if(yDist<5)
yDist=5;
float dist = Vector2Math.distance(planet.position, otherPlanet.position);
//Now we compute first the total and then the component forces
//Depending on choice, use r or r^2
float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist));
float forceX = force * xDist/dist;
float forceY = force * yDist/dist;
//Given the component forces, we construct the force vector and apply it to the body.
Vector2 forceVec = new Vector2(forceX, forceY);
planet.force = Vector2Math.add(planet.force, forceVec);
otherPlanet.force = Vector2Math.subtract(otherPlanet.force, forceVec);
}
当然,您想将5更改为适合您仿真的值。