I'm making a simple, non-networked game. There are two players and a ball. In implementing the AI for the second player, I've run into a huge problem predicting where the ball will hit the ground. Either I've made a mistake in the physics engine or in implementing the prediction itself. I wrote the physics engine, and while it works visually as I expect it to, I won't rule it out as a suspect. First I'd like to make sure I haven't made a mistake in the prediction code. Here's what I have found so far:
I print the predicted time to impact and the accumulated time in each frame. The time predicted for impact is way off.
tti: 0.678233
total time: 0
.
.
tti: 0.0108339
total time: 0.94969
[ball] ground collision
The code for predicting is in two functions.
double nextBallCollisionWithGround(Ball *ball, double groundHeight) {
double timeToImpact = quadraticSolver(kGravity, ball->velocity().y, ball->position().y - ball->radius() - groundHeight);
std::cout << " tti: " << timeToImpact << endl;
double groundPos = -3.;
if (timeToImpact > 0) {
groundPos = ball->velocity().x * timeToImpact + ball->position().x;
}
return groundPos;
}
double quadraticSolver(double a, double b, double c) {
double ans = -1.;
double det = (b*b) - (4.*a*c);
double t1, t2;
if (det > 0.) {
t1 = (-b + sqrt(det)) / (2. * a);
t2 = (-b - sqrt(det)) / (2. * a);
if (t1 > 0.)
ans = t1;
if (t2 > 0.)
ans = t2;
}
return ans;
}
If there's no problem in these functions, I can include the relevant parts of the physics engine to see if the problem is there.
