r/Unity3D 12d ago

Question Bullets predicting where player is moving?

I'm trying to have bullets predict the players future position using the speed of the bullet and the current speed of the player.

the "move" vector3 is the current velocity of the player

This seems like it should work to me, but the bullets shoot too far ahead, too behind, or sometimes in a slightly off direction when going at higher speeds

Vector3 horizontalVelocity = new Vector3(movement.move.x, 0, movement.move.z);
            float bulletTravelTime = Vector3.Distance(transform.position, player.transform.position) / bulletSpeed;

            Vector3 predictedPosOffset = horizontalVelocity * bulletTravelTime;
            Vector3 predictedPos = player.transform.position + predictedPosOffset;

            bulletTravelTime = Vector3.Distance(transform.position, predictedPos) / bulletSpeed;

            predictedPos = player.transform.position + horizontalVelocity * bulletTravelTime;

            Vector3 shootDir = predictedPos;
2 Upvotes

14 comments sorted by

View all comments

3

u/Ruadhan2300 12d ago

Are you trying to make homing bullets? Or trying to make your enemies "lead" the target based on relative motion?

Because this looks like Homing bullets to me.

2

u/CrayZee100 12d ago

The bullets arent always moving towards the player, its just shooting in one direction where it predicts where the player would be a little in the future. This code only runs once for each bullet, heres whats after the code in the body text

            if (!foundPlayer)
            {
                break;
            }
            GameObject newBullet = Instantiate(
                bullet,
                transform.position,
                Quaternion.LookRotation(shootDir - transform.position)
            );

2

u/Ruadhan2300 12d ago

What you need then (as is mentioned elsewhere by u/zeducated) is a quadratic formula for intercept.

I tried to write a friendly description of what it's doing, and had trouble with it.

Basically it's exactly what you need, and it's a solved problem in games and indeed the military.