我在Objective-C中實現了問題「Ball to Ball Collision - Detection and Handling」中的代碼。但是,每當球以一定角度碰撞時,其速度就會急劇增加。所有的矢量數學運算使用cocos2d-iphone,頭CGPointExtension.h完成。這種不希望的加速度的原因是什麼?球對球碰撞 - 在碰撞時獲得顯着的速度
以下是在速度增加的一個示例:
輸入:
質量== 12.56637
velocity.x == 1.73199439
velocity.y == -10.5695238
球.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));
}
你的物理是這裏的問題:您正在設置不節約動能的碰撞,因爲恢復係數爲1.75(超過1)。 因此,這不是一個編程相關的錯誤。 – jpinto3912 2009-05-21 21:03:44
你可以發佈你的代碼有效的最終版本嗎? – 2009-05-21 22:45:04