Time for action – getting ready to fire
The enemy will shoot in a similar manner to how the player fires, but we will use some basic AI to control the direction and firing speed, replacing the player's input controls:
We will start this off with a new script called
ShootAtPlayer
. Create it in theScripts
folder.As with all our other scripts, we start this one out with two variables. The first variable will hold the last position the enemy tank was at. It will not be shooting if the tank is in motion, so we need to store that last position to see if we have moved. The second variable will be the maximum speed at which we can move and shoot. If the tank moves faster than this, it will not fire.
private Vector3 lastPosition = Vector3.zero; public float maxSpeed = 1f;
The next two variables dictate how long it takes the tank to ready a shot. It is unrealistic to be shooting the player in every single frame. So, we use the first variable to adjust the length of time it takes to ready a shot, and...