Calculating a Trajectory
Posted: Tue Jan 05, 2010 8:41 am
I've hacked together the following method that should, given a projectiles initial position, target position and a random velocity, calculate the required angle in order for the projectile to hit a target.
My physics is dire, so I'm stumbling through this with help from wikipedia. The above method results in a very weak impulse being applied to the projectile which I suspect has something to do with chipmunk coordinates vs screen coordinates. I know box2d has the PTM_RATIO, but i've been unable to locate anything like that in chipmunk.
If any of you physics boffins can see an error in the formulae, or if anyone knows of some chipmunk feature that I've not used then I'd really appreciate any help in figuring this out.
cheers
-t
Code: Select all
- (void) calculateShotForTarget:(CGPoint)target from:(CGPoint)launchPos
{
float x = target.x = launchPos.x;
float y = target.y = launchPos.y;
float g = 9.8;
float v = 100; // this will be picked at random from a range
float angle1, angle2;
float tmp = pow(v, 4) - g * (g * pow(x, 2) + 2 * y * pow(v, 2));
if(tmp < 0){
NSLog(@"No Firing Solution");
}else{
angle1 = atan2(pow(v, 2) + sqrt(tmp), g * x);
angle2 = atan2(pow(v, 2) - sqrt(tmp), g * x);
}
// Does anyone know what this does? I thought it may be the answer.
//cpVect angleCPV = cpvforangle(angle1);
angle1 = angle1 * (180 / M_PI);
angle2 = angle2 * (180 / M_PI);
// Get the horizontal and vertical velocities
float vVel = v * sin(angle2);
float hVel = v / tan(angle2);
CGPoint force = cpv(hVel, vVel);
// LaunchData is a convenience class for passing CGPoints around.
LaunchData *shot = [[[LaunchData alloc] initWithForce:force andPosition:launchPos] autorelease];
[[NSNotificationCenter defaultCenter] postNotificationName:PlayerDidFinishAiming object:shot];
}
If any of you physics boffins can see an error in the formulae, or if anyone knows of some chipmunk feature that I've not used then I'd really appreciate any help in figuring this out.
cheers
-t