And*_*ndt 4 graphics physics objective-c collision-detection
我在Objective-C中实现了" Ball to Ball Collision - Detection and Handling " 问题的代码.然而,每当球以一定角度碰撞时,它们的速度会急剧增加.所有的矢量数学都是使用cocos2d-iphone完成的,标题为CGPointExtension.h.这种不希望的加速的原因是什么?
以下是速度提高的示例:
输入:
质量== 12.56637
velocity.x == 1.73199439
velocity.y == -10.5695238
ball.mass == 12.56637
ball.velocity.x == 6.04341078
ball.velocity.y == 14.2686739
输出:
质量== 12.56637
velocity.x == 110.004326
velocity.y == -10.5695238
ball.mass == 12.56637
ball.velocity.x == -102.22892
ball.velocity.y == -72.4030228
#import "CGPointExtension.h"
#define RESTITUTION_CONSTANT (0.75) //elasticity of the system
- (void) resolveCollision:(Ball*) ball
{
// get the mtd (minimum translation distance)
CGPoint delta = ccpSub(position, ball.position);
float d = ccpLength(delta);
// minimum translation distance to push balls apart after intersecting
CGPoint mtd = ccpMult(delta, (((radius + ball.radius)-d)/d));
// resolve intersection --
// inverse mass quantities
float im1 = 1 / [self mass];
float im2 = 1 / [ball mass];
// push-pull them apart based off their mass
position = ccpAdd(position, ccpMult(mtd, (im1 / (im1 + im2))));
ball.position = ccpSub(ball.position, ccpMult(mtd, (im2 / (im1 + im2))));
// impact speed
CGPoint v = ccpSub(velocity, ball.velocity);
float vn = ccpDot(v,ccpNormalize(mtd));
// sphere intersecting but moving away from each other already
if (vn > 0.0f) return;
// collision impulse
float i = (-(1.0f + RESTITUTION_CONSTANT) * vn) / ([self mass] + [ball mass]);
CGPoint impulse = ccpMult(mtd, i);
// change in momentum
velocity = ccpAdd(velocity, ccpMult(impulse, im1));
ball.velocity = ccpSub(ball.velocity, ccpMult(impulse, im2));
}
Run Code Online (Sandbox Code Playgroud)
通过原始海报审查了原始代码和注释后,代码看起来是一样的,所以如果原始代码是正确的实现,我会怀疑一个坏的矢量库或某种未初始化的变量.
为什么要在恢复系数上加1.0?
来自:http://en.wikipedia.org/wiki/Coefficient_of_restitution
COR通常是[0,1]范围内的数字.定性地,1表示完全弹性碰撞,而0表示完全非弹性碰撞.大于1的COR在理论上是可能的,表示产生动能的碰撞,例如地雷被抛在一起并爆炸.
另一个问题是:
/ (im1 + im2)
Run Code Online (Sandbox Code Playgroud)
你用除了质量的倒数之和来得到沿着接触向量的冲动 - 你可能应该除以质量本身的总和.这是放大你的冲动("这就是她所说的").
| 归档时间: |
|
| 查看次数: |
3427 次 |
| 最近记录: |