Thank you guys, It’s helpful very much! and you are right I should past my codes.
I’d like to know where to call the “TheFunctionWhereYouSeeThePlayer()”? For now I call it in Update(), but the enemy will catch the updating position of player when play were moving. I am confused.
I define my enemy’s behavior like this: If the distance between it and player is within 20 units, the enemy will stop wandering, stand for one second and chenage color to Red for “angry”. then move “attack” to the old position of player when it saw player. If player was not at the old position and the distance is still within 20 units the enemy would attack player again. This would be loop with 20 units distance.
Sorry for my english.
Thanks,
I past my codes below.(I am a new hand of coding :P)
PS: 1, I use navmesh as the way of wandering. 2, I use iTween.MoveTo to attack.
public class SampleAgentScript : MonoBehaviour {
public Transform Player;
Privat NavMeshAgent agent;
Privat Transform myTransform;
public Vector3 randomTarget;
public float range;
public float distance;
public float colorTime;
void Awake ()
{
myTransform = gameObject.transform;
agent = GetComponent();
range = 4;
colorTime = 1.0f;
Wander();
gameObject.renderer.material.color = Color.white;
}
void Update ()
{
distance = Vector3.Distance(Player.position, gameObject.transform.position);
if (distance < 20)
{
StartCoroutine(SeeingPlayer());
}
if (distance > 20)
{
if ((myTransform.position - randomTarget).magnitude < range)
{
Wander();
}
}
}
IEnumerator SeeingPlayer()
{
//set the player position as target Position attacking to;
randomTarget = Player.position;
//change into attcking color;
Color lerpColor = Color.Lerp(gameObject.renderer.material.color, Color.red, Time.deltaTime * 3f);
gameObject.renderer.material.color = lerpColor;
//slow down move speed to zero;
agent.speed -= 0.5f;
if (agent.speed < 0)
agent.speed = 0;
//wait for 1 second;
yield return new WaitForSeconds(1);
//move to player old position.
iTween.MoveTo(gameObject, iTween.Hash("position", randomTarget,"time", 1f, "looktarget", randomTarget, "easetype", iTween.EaseType.linear));
}
void Wander()
{
//set wander speed;
agent.speed = 3.5f;
//set a random position that enemy move to;
randomTarget = new Vector3((float)Random.Range(-50, 50), 0.0f, (float)Random.Range(-50, 50));
agent.SetDestination(randomTarget);
//change into wander color;
Color lerpColor = Color.Lerp(gameObject.renderer.material.color, Color.white, Time.deltaTime * 40f);
gameObject.renderer.material.color = lerpColor;
}