Dev Day 66: Using Lerp-Over-Time to Evade Shots in Unity3D
Objective: When the Enemy detects a laser, depending on which Raycast picks up the detection, the Enemy will move to the left or right to evade the laser.
Step 1: Create an IEnumerator method called DodgeLeft(). Within this method create a Vector2 variable called _currentPos and have it equal to transform.position. Create another Vector2 variable called _destination and have that equal to a new Vector2 with the current transform position on the X-axis minus 1, and the current transform position on the Y-axis. Then create a float variable called _t and have it equal to 0.
Step 2: Create a while loop stating that while _t is less than 1, _t will equal _t plus Time.deltaTime divided by 0.1f. Then, the transform’s position will equal Vector2.Lerp using the _currentPos value, the _destination value, and the _t value, which will increment with each loop cycle. Then use yield return null to have the while loop restart each frame until _t is not less than 1.
Step 3: Create another IEnumerator method called DodgeRight() and repeat the above process, but in the _destination variable declaration, change the transform.position.x to plus 1 so the Enemy moves to the right on the screen.
Step 4: In the LaserDetecttionRaycast() method, start the DodgeRight() coroutine within the _laserDetectionLeft if statement, and call the DodgeLeft() coroutine within the _laserDetectionLeft if statement.
Save the script, go back into Unity, and when the Enemy detects a laser on the left side, it will dodge to the right, and if it detects the laser on the right side, it will dodge to the left.