Hi all,
This problem has been plaguing me for about 2 weeks now and I cant seem to crack it.
I have a simple state machine for the enemy. The enemy chases the player until the player reaches a light source. Once the player reaches a light source, the enemy retreats. This all works except i want the enemy to stop retreating a certain distance from the player.
At the moment, the enemy is retreating indefinitely until the player leaves the light in which the enemy once again, gives chase.
As you can see in the Retreat function below, I have tried a few methods but none seem to do exactly what I want.
Pastie here or code below: http://pastie.org/private/tjfb3r1xzemmm05dele0wa
Thanks for the help in advance, I really appreciate it.
using UnityEngine;
using System.Collections;
public class DarkChase : MonoBehaviour {
public float maxAdvanceSpeedY = 1.0f;
public float maxAdvanceSpeedX = 1.0f;
public float maxRetreatSpeedY = 1.0f;
public float maxRetreatSpeedX = 1.0f;
public float minDistance = 5.0f;
//public float maxRetreatDistance = 100.0f;
//public float maxDistance = -10.0f;
public GameObject Player;
public GameObject theDark;
public PlayerControl thePlayerScript;
//public Transform Target;
// Use this for initialization
void Start () {
Player = GameObject.FindGameObjectWithTag("Player");
thePlayerScript = thePlayerScript.GetComponent<PlayerControl>();
}
// Update is called once per frame
void Update () {
if (PlayerControl.inLight == false)
Advance();
else if (PlayerControl.inLight == true)
Retreat();
}
public void Advance () {
print ("Advance");
Vector3 playerPosition = Player.transform.position;
Vector3 darkPosition = transform.position;
Vector3 difference = darkPosition - playerPosition;
difference.Normalize();
transform.Translate (
(difference.x * -maxAdvanceSpeedX), (difference.y * -maxAdvanceSpeedY), (difference.z * -1));
}
public void Retreat () {
print ("Retreat");
Vector3 playerPosition = Player.transform.position;
Vector3 darkPosition = transform.position;
Vector3 difference = darkPosition + playerPosition;
difference.Normalize();
transform.Translate (
(difference.x * +maxRetreatSpeedX), (difference.y * +maxRetreatSpeedY), (difference.z * +1));
float dist = Vector3.Distance(playerPosition, darkPosition);
if (Vector3.Distance (playerPosition, darkPosition) <= minDistance)
Debug.DrawLine (playerPosition, darkPosition, Color.yellow);
print ("Distance to player: " + dist);
//darkPosition = Vector2.MoveTowards (transform.position, playerPosition, maxAdvanceSpeedX * Time.deltaTime);
//transform.Translate (
//(maxDistance), (0), (0));
//Vector3 maxDistance = Vector3.Distance (playerPosition, darkPosition);
//if (maxDistance >= maxRetreatDistance)
//.Translate (
//(difference.x - maxRetreatDistance), (difference.y - 0.01), (difference.z - 0.01));
}
}