Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Tutorial - Make (Mostly) Accurate Projectile Throwing AI at Moving Targets | AI Series Part 41

Discussion in 'Community Learning & Teaching' started by ChrisKurhan, Aug 30, 2022.

  1. ChrisKurhan

    ChrisKurhan

    Joined:
    Dec 28, 2015
    Posts:
    266


    Hey all! Happy #TutorialTuesday!

    This week you can learn how to make scary-accurate projectile throwing AI! This week I'll cover some math you probably already learned and forgot, but in a more fun way...where we'll make some AI throw balls at us and hit us repeatedly!

    The AI Series is near and dear to my heart. I've had a lot of fun covering a wide variety of topics and this one (Episode 41!) did not disappoint either!

    As always, the full project code is available on GitHub for you to play around with.

    Most stuff I saw about projectile motion requires you to know a starting point, ending point, max height, and/or initial/final velocity (3 of these are required to use the Kinematic Equations). This ends up being one too many variables to solve for in most AI cases. You can however, use some cool trigonometry (and other associated maths) to find out that the angle required to throw at is easily calculable from the origin and target position.

    With that information, we can calculate the initial velocity required to throw something at that particular angle.

    With that part done, you can then find out how long it takes to get to the target given the time it takes for the projectile to reach the current target position and extrapolate the target's position at X time in the future based on your favorite method of guessing - current instantaneous velocity, historical velocity over the last Y seconds, or some other method.

    Current instantaneous velocity is relatively straightforward, I took it from the CharacterController.velocity then calculated the force required to hit the player using the same equations above assuming that the player would continue along that direction.

    Historical Velocity Projection is a little more cumbersome because we have to track the previous locations over Y seconds and then find out the average velocity (or your other preferred method) and project where the player will be based on that average. The longer duration and more samples you take, the more computationally (and memory) expensive this becomes. We also have to update the initial throw velocity based on the _new time_ it takes to go from launch point to hit point, otherwise we can get there too slow or too fast!

    If nothing else, it is fun getting hit by all these balls