- Home /
AI Enemy Follow Player
I have created a script to make the enemy follow the player. But I have some small isssues, and I cant figure out how to fix them.
I want the enemy to face the player all the time. So I need a form of rotation.
I want the enemy to dissapear or die, when he touches the player.
How can I stop the enemy from following the player all the time? Its just following the player all the time.
Here is my script:
public float speed;
private Transform target;
// Use this for initialization
void Start () {
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
if you want your enemy to follow you only at particular situations use if/else syntax in update method dont use your syntax directly in update
Answer by davidcox70 · Apr 18, 2018 at 06:49 PM
A few pointers....
You have used MoveTowards to make your enemy follow the player. There is also Transform.LookAt and Vector3.RotateTowards. Find these in the docs and you should be able to make your enemy face your player.
To make your enemy die when he touches the player, look up colliders and then in a script attached to the enemy gameobject, try something like;
void OnCollisionEnter(collision col){
// change player name for the name of your players game object
if (col.gameObject.name=="playerName"){
Destroy(gameObject);
}
To stop the enemy following the player, look into IF conditional statements. For example;
if (enemyShouldFollow){
// enemy will now only follow if the boolean enemyShouldFollow is true
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
Answer by aloshegamer · Mar 22, 2020 at 07:49 PM
What about rotation please reply
For Rotate (This works in 3D, I didn't test it for 2D)
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.position, speed * Time.deltaTime);
transform.LookAt(target.position); //With this line the obj rotate
The Z axis is the front of the rotation