Notes:
- 0:20 What you’ll be making.
- 1:17 Placeholder Graphics. Graphics don’t matter for this tutorial as long as you can follow along and make the final product.
- 1:32 Add a box collider to the platform.
- 1:41 Create a new script called Patrol
- 1:50 Delete the Start and Update functions and create a public variable of type float called speed.
- 2:04 Create a private variable of type bool called moving right and set it equal to true.
- 2:19 Make a public variable of type Transform called ground detection.
- 2:26 Create an empty game object called ground detection.
- 2:28 Add a gizmo to it to easily detect it in the Scene view.
- 2:36 Make it a child of the patrolling AI.
- 2:42 Place it in front of the character and slightly above ground level.
- 2:46 We will be shooting out an invisible ray from this empty game object. If the ray no longer detects any collisions, the AI will move in the other direction.
- 3:35 Move the AI forward.
- 3:56 Create a RaycastHit2D below that line.
- 4:01 Set it equal to Physics2D.Raycast.
- 4:13 In the parentheses feed in the origin of the ray (ground detection), the direction our ray will travel in (downwards), and the distance of our ray (2f)
- 5:03 Check if the ray has hit anything
- 5:23 In that if statement, check if the player was moving right.
- 5:46 If the AI was moving right and they’ve reached the edge, it’s time for them to face the opposite direction to move left.
- 5:55 Below that line, set moving right to false.
- 6:15 Add an else clause to that if statement to set the AI back to default rotation if it was moving left and set moving right back to true.
- 6:27 Save and close the Patrol script. Drag and drop the ground detection empty in the empty Transform slot in the inspector.
- 6:31 Type in some value for speed.