- Home /
I have a problem with my enemy AI script
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
}
}
}
On Line 30: Should that not be < maxDistance? At the moment if the enemy is outside that distance it will follow the player. I'm assu$$anonymous$$g you want it the opposite.
Answer by robcbryant · Mar 17, 2014 at 07:50 PM
What Bash Mills said: Right now if the distance between the enemy and player is greater than 'zero' it will always follow the player.
maxDistance needs to be set to 15 and you need to change the if statement to this:
if(Vector3.Distance(target.position, myTransform.position) < maxDistance)
This way it will only follow the player if it's within 15 units and do nothing if it's further away.
Your answer
Follow this Question
Related Questions
Why is my gameObject falling so slow? 1 Answer
2d collider stuck issue 1 Answer
Trying to get Player Tip for player to open on Return and close on Return 2 Answers
2D Sidescroller enemy AI jump help! Picture Included! 3 Answers
Jump 2D error 1 Answer