Hey guys.
How can I change the script, when the player is near to the enemy(without a collider, because I have a SendDamageCollider script on the enemy) then should the enemy start to follow the player(as an example: if the distance are less then 15, the enemy should start to follow the player).
When the position of the enemy is at the end and the player is at the beggining, the enemy follow the player everywhere and that's not good.
It's a 2D platformer game. I hope that i could explain it.
Here is the script:
using UnityEngine;
using System.Collections;
public class EnemyAi : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
public int maxDistance;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
maxDistance = 0;
}
// Update is called once per frame
void FixedUpdate () {
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
if (target.position.x < myTransform.position.x) myTransform.position -= myTransform.right * moveSpeed * Time.deltaTime; // player is left of enemy, move left
else if (target.position.x > myTransform.position.x) myTransform.position += myTransform.right * moveSpeed * Time.deltaTime; // player is right of enemy, move right
}
}
}
↧