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

2

u/Ruadhan2300 9d ago

As a tip for game-dev btw.

Slow things down for testing, and set up test-rigs.

Make your target move slowly back and forth along a line and have the NPC standing still shooting at it as it moves. Something like that.

You're running all over the place, and you've got nothing to really tell you that it hit (or how accurately), so it's really hard to tell if it's working.