gpt4 book ai didi

java - 物理圈碰撞弹出和滑动边界

转载 作者:搜寻专家 更新时间:2023-10-31 20:00:46 26 4
gpt4 key购买 nike

在 Java 中,我正在为 Android 编写一个移动应用程序,以使用我自己编写的一些类与一些动态球进行交互。重力取决于手机的倾斜度。

我注意到,当我将一堆球聚集在一个角落时,其中一些会开始抖动,或者有时会在与其他球碰撞时滑动。这可能是因为我以错误的顺序执行步骤吗?

现在我有一个循环遍历每个球:

  • 模拟一次迭代
  • 检查与其他球的碰撞
  • 检查场景边界的碰撞

我应该补充一点,我与边界有摩擦,当球与球发生碰撞时,只是为了失去能量。

以下是如何处理碰撞的部分代码:

    // Sim an iteration
for (Ball ball : balls) {
ball.gravity.set(gravity.x, gravity.y);

if (ball.active) {
ball.sim();

// Collide against other balls
for (Ball otherBall : balls) {
if (ball != otherBall) {
double dist = ball.pos.distance(otherBall.pos);
boolean isColliding = dist < ball.radius + otherBall.radius;
if (isColliding) {
// Offset so they aren't touching anymore
MVector dif = otherBall.pos.copy();
dif.sub(ball.pos);
dif.normalize();
double difValue = dist - (ball.radius + otherBall.radius);
dif.mult(difValue);
ball.pos.add(dif);

// Change this velocity
double mag = ball.vel.mag();
MVector newVel = ball.pos.copy();
newVel.sub(otherBall.pos);
newVel.normalize();
newVel.mult(mag * 0.9);
ball.vel = newVel;

// Change other velocity
double otherMag = otherBall.vel.mag();
MVector newOtherVel = otherBall.pos.copy();
newOtherVel.sub(ball.pos);
newOtherVel.normalize();
newOtherVel.mult(otherMag * 0.9);
otherBall.vel = newOtherVel;
}
}
}
}
}

最佳答案

如果这是检查球之间相互作用的唯一代码,那么问题似乎很清楚。一个球不可能在平衡状态下停在另一个球的上面。

假设您将一个球直接放在另一个球之上。当您计算由于重力引起的顶部球的加速度时,您还应该像您发布的那样进行碰撞检查,除了这次检查 dist <= ball.radius + otherBall.radius。 .如果是这种情况,那么您应该假设球之间的法向力等于重力,并抵消与连接两个球中心的 vector 一致的重力分量。如果您不这样做,那么顶部的球将加速进入底部的球,触发您发布的碰撞代码,您会感到紧张。

当球与场景边界接触时必须使用类似的逻辑。

关于java - 物理圈碰撞弹出和滑动边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35671801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com