Algorithm to shoot at a target in a 3d game

Posted by Sebastian Bugiu on Game Development See other posts from Game Development or by Sebastian Bugiu
Published on 2012-09-11T13:01:59Z Indexed on 2012/09/11 15:50 UTC
Read the original article Hit count: 264

Filed under:
|
|
|

For those of you remembering Descent Freespace it had a nice feature to help you aim at the enemy when shooting non-homing missiles or lasers: it showed a crosshair in front of the ship you chased telling you where to shoot in order to hit the moving target.

I tried using the answer from http://stackoverflow.com/questions/4107403/ai-algorithm-to-shoot-at-a-target-in-a-2d-game?lq=1 but it's for 2D so I tried adapting it.

I first decomposed the calculation to solve the intersection point for XoZ plane and saved the x and z coordinates and then solving the intersection point for XoY plane and adding the y coordinate to a final xyz that I then transformed to clipspace and put a texture at those coordinates. But of course it doesn't work as it should or else I wouldn't have posted the question.

From what I notice the after finding x in XoZ plane and the in XoY the x is not the same so something must be wrong.

    float a = ENG_Math.sqr(targetVelocity.x) + ENG_Math.sqr(targetVelocity.y) -
            ENG_Math.sqr(projectileSpeed);
    float b = 2.0f * (targetVelocity.x * targetPos.x + 
            targetVelocity.y * targetPos.y);
    float c = ENG_Math.sqr(targetPos.x) + ENG_Math.sqr(targetPos.y);
    ENG_Math.solveQuadraticEquation(a, b, c, collisionTime);

First time targetVelocity.y is actually targetVelocity.z (the same for targetPos) and the second time it's actually targetVelocity.y.

The final position after XoZ is

    crossPosition.set(minTime * finalEntityVelocity.x + finalTargetPos4D.x, 0.0f, 
                minTime * finalEntityVelocity.z + finalTargetPos4D.z);

and after XoY

    crossPosition.y = minTime * finalEntityVelocity.y + finalTargetPos4D.y;

Is my approach of separating into 2 planes and calculating any good? Or for 3D there is a whole different approach?

  • sqr() is square not sqrt - avoiding a confusion.

© Game Development or respective owner

Related posts about engine

Related posts about math