Skip to main content
 首页 » 编程设计

c#之如果 body 撞得太快,区域限制会破坏我的物理模拟

2024年02月24日12lyhabc

我有一个物理模拟,它允许你设置区域限制,这样里面的物体就不会离开那个区域。然而,如果一个原子越过面积约束的其中一堵“墙”,它就会破坏物理模拟。为什么要这样做? 更新方法:

if (!atom.IsStatic) 
{ 
    Vector2 force = Vector2.Zero; 
    bool x = false, y = false; 
    if (atom.Position.X - atom.Radius < _min.X) 
    { 
        force = new Vector2(-(_min.X - atom.Position.X), 0); 
        if (atom.Velocity.X < 0) 
            x = true; 
    } 
    if (atom.Position.X + atom.Radius > _max.X) 
    { 
        force = new Vector2(atom.Position.X - _max.X, 0); 
        if (atom.Velocity.X > 0) 
            x = true; 
    } 
    if (atom.Position.Y - atom.Radius < _min.Y) 
    { 
        force = new Vector2(0, -(_min.Y - atom.Position.Y)); 
        if (atom.Velocity.Y < 0) 
            y = true; 
    } 
    if (atom.Position.Y + atom.Radius > _max.Y) 
    { 
        force = new Vector2(0, atom.Position.Y - _max.Y); 
        if (atom.Velocity.Y > 0) 
            y = true; 
    } 
    atom.ReverseVelocityDirection(x, y); 
    if (!atom.IsStatic) 
    { 
        atom.Position += force; 
    } 
} 

请您参考如下方法:

我看到您正在使用恒定时间步长 T 进行计算。当通过在每一步上模拟碰撞时,您应该使用等于任何原子到达任何障碍物之前的最短时间的时间步长。 p>

使时间步可变,原子永远不会“隧道”障碍。

附言碰撞检测有很多优化,请阅读 gamedev 论文以获取相关信息。

附言错误?

force = new Vector2(-(_min.X - atom.Position.X), 0); 

力是为 X 和 Y 反射单独创建的。当原子进入一个角落时会发生什么?只会施加第二个力。

P.P.S:使用 epsilon

一个更重要的注意事项:如果你使用 float ,误差会累积,你应该使用eps:

abs(atom.Position.Y + atom.Radium - _max.Y) < eps 

其中 eps 是一个比任务中的正常大小小得多的数字,例如0.000001.