- Home /
Follow Player when Close C# Help
Hi Guys! :) I have a script here and i need help how do i do so The AI Follows player just when the player is Close? I have a Script Temp Already here :D :
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 = 1;
}
// Update is called once per frame
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
if(Vector3.Distance(target.position, myTransform.position) > maxDistance) {
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Any Ideas :)?
What is the specific problem: What does it do now and how do you want that to change?
This looks like it should move closer until it gets to 1 unit away, which seems fine (but it measures center to center, so if you used normal sized cubes, 1 unit away is touching.)
I want to make so If a Player Touches/Walk near the Enemy. It starts to Follow it until the enemy / player dies
Answer by fafase · Apr 22, 2012 at 05:14 PM
Ok, this would be a simple version. You have your target (player) that you drag in the inspector. Then it compares the position of each and if smaller than a range the NPC looks at the player and walk towards him. If the NPC gets too close, it stops walking. This way your guy is keeping its distance from the player and just follows him around.
var target :Transform;
var maxRange:int;
var minRange:int;
if((Vector3.Distance(transform.position,target.position)<maxRange)
&& (Vector3.Distance(transform.position,target.position)>minRange)){
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime);
}
Now if you want the NPC to follow no matter what
var target :Transform;
var minRange:int;
var follow:boolean;
function Update(){
if(Vector3.Distance(transform.position,target.position)<minRange)
follow=true;
if(follow){
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime);}
}
Now your guy will start follow when you get close and since the boolean never changes it will follow you till death.
but i get a Error:
Assets/Scripts/AI Follow.js(7,13): BCE0005: $$anonymous$$ identifier: 'Distance'.
Your answer
Follow this Question
Related Questions
AI Follow Player "Tag" Help 1 Answer
Follow Player Via Waypoints 1 Answer
AI Help FPS 0 Answers
Camera rotation around player while following. 6 Answers
Change AI Follow Players 1 Answer