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.