题
我试图使物理体以随机速度的随机位置生成,以达到目标。我从使用Chipmunk在Box2D中运行的网络中收集并稍微修改了此代码
+ (CGPoint) calculateShotForTarget:(CGPoint)target from:(CGPoint) launchPos with:(float) velocity
{
float xp = target.x - launchPos.x;
float y = target.y - launchPos.y;
float g = 20;
float v = velocity;
float angle1, angle2;
float tmp = pow(v, 4) - g * (g * pow(xp, 2) + 2 * y * pow(v, 2));
if(tmp < 0){
NSLog(@"No Firing Solution");
}else{
angle1 = atan2(pow(v, 2) + sqrt(tmp), g * xp);
angle2 = atan2(pow(v, 2) - sqrt(tmp), g * xp);
}
CGPoint direction = CGPointMake(cosf(angle1),sinf(angle1));
CGPoint force = CGPointMake(direction.x * v, direction.y * v);
NSLog(@"force = %@", NSStringFromCGPoint(force));
NSLog(@"direction = %@", NSStringFromCGPoint(direction));
return force;
}
问题是我不知道如何将其应用于我的程序,我的重力为-20,但为g投入20,而较低的速度像10的v速度为v,除了“没有射击解决方案”,我什么都没有。
我究竟做错了什么?
解决方案
较低的速度为10永远不会起作用。弹丸没有足够的动力来行驶距离。
计算中的错误是,除了像素中的距离计算外,所有内容均为米!
将代码更改为此修复了我得到的疯狂速度:
+ (CGPoint) calculateShotForTarget:(CGPoint)target from:(CGPoint) launchPos with:(float) velocity
{
float xp = (target.x - launchPos.x) / PTM_RATIO;
float y = (target.y - launchPos.y) / PTM_RATIO;
float g = 20;
float v = velocity;
float angle1, angle2;
float tmp = pow(v, 4) - g * (g * pow(xp, 2) + 2 * y * pow(v, 2));
if(tmp < 0){
NSLog(@"No Firing Solution");
}else{
angle1 = atan2(pow(v, 2) + sqrt(tmp), g * xp);
angle2 = atan2(pow(v, 2) - sqrt(tmp), g * xp);
}
CGPoint direction = CGPointMake(cosf(angle1),sinf(angle1));
CGPoint force = CGPointMake(direction.x * v, direction.y * v);
NSLog(@"force = %@", NSStringFromCGPoint(force));
NSLog(@"direction = %@", NSStringFromCGPoint(direction));
return force;
}
不隶属于 StackOverflow