Game Development Reference
In-Depth Information
public EnemyControllerScriptenemyObject = null;
void OnTriggerExit2D( Collider2D otherObj )
{
// If this trigger just left a Platform object,
//then the enemy is about to walk off the platform.
//Tell the enemy that they need to switch
//directions!
if(otherObj.tag == "Platform")
enemyObject.switchDirections();
}
}
5.
Attach
EnemyGuideWatcher
to both the
LeftGuide
and the
RightGuide
objects and make sure to add the
Enemy
object to the
Enemy Object
ield
on both objects in the
Inspector
panel.
Next, we need to make sure the enemy knows how to flip its direction by reversing
its movement direction, just like we did with the player back in
Chapter 1
,
Introduction to the 2D World of Unity
. Go back to
EnemyControllerScript
and give it some code. Fill the script with the following code:
using UnityEngine;
using System.Collections;
public class EnemyControllerScript : MonoBehaviour
{
public float walkingSpeed = 0.45f;
private bool walkingLeft = true;
void Start()
{
// Randomly default the enemy's direction
walkingLeft = (Random.Range(0,2) == 1);
updateVisualWalkOrientation();
}
void Update()
{
// Translate the enemy's position based on the direction
// that they are currently moving.
if(walkingLeft)
{
transform.Translate(new Vector3(walkingSpeed *