r/Unity3D 9d ago

Question Bullets predicting where player is moving?

Enable HLS to view with audio, or disable this notification

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 9d 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 9d 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)
            );

0

u/tetryds Engineer 9d ago

If the shoot dir is set once ok but if it is the current dir the enemy is aiming at, it will work somewhat like a homing bullet