Unity3D Enemy AI Script to Anticipate Player’s Future Position

Last night I needed to make my enemies a bit more difficult for my Super Space Troopers indie video game.  Because my player is always moving forward, enemies that fire directly at the player’s current position would never actually hit the player.  So I needed a way to anticipate where the player would be when the enemy’s weapons reached the player’s position.

This source code is incomplete, however it is the part that does the anticipation.  Please feel free to use or improve upon it.

/* Written by Cassius Adams for the Super Space Trooper video game. http://www.SuperSpaceTrooper.com */
// Find the distance between weapon and Player so we can anticipate where Player will be
distance = Vector3.Distance(player.transform.position, transform.position);
 
// Divide distance by weaponSpeed to see how long it will take to get from Enemy to Player
var travelTime = distance / (Mathf.Abs(weaponSpeed) + playerSpeed);
 
// Multiply the amount of time by the speed the Player moves at
var futurePosition = travelTime * playerSpeed;
 
// Assign the new location that we want to point the weapons towards
var newLocation = Vector3(player.transform.position.x, player.transform.position.y, player.transform.position.z + futurePosition);
 
// Look at and dampen the rotation
var rotation = Quaternion.LookRotation(newLocation - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);

You will obviously need to set your playerSpeed, damping time, and (enemy) weaponSpeed.

Cheers!

Posted in Javascript JS, Super Space Trooper, Unity 3D, Video Game Development
0 comments on “Unity3D Enemy AI Script to Anticipate Player’s Future Position
2 Pings/Trackbacks for "Unity3D Enemy AI Script to Anticipate Player’s Future Position"
  1. […] They would always miss.  So for the second, more important script, I wrote one that would predict the player’s future position and point the enemies in that direction instead.  That way when they fire, unless the player specifically moves out of the way they’re going […]

  2. […] case you’re interested in checking out the source code, you can find the player’s future position sourcecode here. Posted in Enemies, Super Space Trooper, Unity 3D, Video Game […]

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>