So I have a script that takes the enemy and moves it between its starting position and the transform position of another hidden game object. The script works fine for the movement. However, I want the script to only run if the player isn’t seen and then resume playing once the player is not seen once again. I have it tracking the location, but when I switch the bool, it jumps forward like the script was still working even though that code should not be running anymore due to the flag being set. I want it to stop and resume from the same place, but I’m hitting a wall at figuring it out. Code below:
#region Notes Section
/*
Author: Paul Christopher
Use: This code handles movement for the enemies
Notes: Enemy moves back and forth at a random speed to a target point and back. (Cycle repeats)
*/
#endregion
using UnityEngine;
using System;
using System.Collections;
public class EnemyMovement : Enemy {
#region Variables
//Movement Target
public Transform farEnd;
//Locations
private Vector3 startLoc;
private Vector3 targetLoc;
private Vector3 currentLoc;
//Time to complete one length
System.Random rnd = new System.Random();
public float secondsToComplete;
#endregion
#region Start
// Use this for initialization
void Start ()
{
//Movement
startLoc = transform.position;
targetLoc = farEnd.position;
//Random
secondsToComplete = rnd.Next(5, 15); //Sets random to be between 5 & 15 inclusive
}
#endregion
#region Update
// Update is called once per frame
void Update ()
{
//Move if player is not seen
if (!playerSeen)
{
StartCoroutine("Movement");
}
if (playerSeen)
{
StopCoroutine("Movement");
transform.position = currentLoc;
}
}
#endregion
IEnumerator Movement()
{
//Moves enemy model between starting location (currentLoc) and a point (targetLoc).
//Model will continually move back and forth (as of right now)
transform.position =
Vector3.Lerp(startLoc, targetLoc,
Mathf.SmoothStep(0f, 1f,
Mathf.PingPong(Time.time / secondsToComplete, 1f)));
currentLoc = transform.position;
yield return null;
}
//END OF FILE BELOW
}