- Home /
Follow within a certain distance?
This script makes my enemy come towards the player when the scene starts, Ive been trying to change it so it only follows me when Im in a certain distance of it. Ive tried over and over but I keep getting errors, Im sure its not that hard to do but if anyone could help me I would be greatfull.
This is the script I haven't tried to change.
var target : Transform;
var moveSpeed = 5;
var rotationSpeed = 5;
var myTransform : Transform;
function Awake () {
myTransform = transform;
}
function Start () {
target = GameObject.FindWithTag("Player").transform;
}
function Update () {
var dist = Vector3.Distance(target.position, myTransform.position);
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
myTransform.rotation = Quaternion.Slerp( myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime );
if(dist > 0.5){
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
It might be tough for you to get an answer without more specifics. The best advice I can give you is to get as close as you can on your own, then let us know the specific error you are seeing (from the console, or from the build output in $$anonymous$$ono). Is there a version of your script that works all the time, and it only breaks when you try to add the proximity detection? Specific is good!
I just formatted your code, all those spaces ....
Start by Debugging. Add this line before the distance conditional check :
Debug.Log( "dist " + dist );
does this return any values over 0.5, or indeed over zero? I have a feeling that maybe you have tagged the enemy as "Player" if target.position is not returning null, or is that the errors you mentioned but never posted. Check that you have indeed tagged the player as "Player" !
Answer by SergeantBiscuits · Oct 02, 2012 at 07:10 PM
Just add a if(dist < 'maximum distance') qualifier. For instance, if you want your enemy to "aggro" at 10 meters, your Update() function could look like this:
function Update () {
var dist = Vector3.Distance(target.position, myTransform.position);
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
if(dist < 10){
myTransform.rotation = Quaternion.Slerp( myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime );
if(dist > 0.5){
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
You can change that "10" to something like "aggroDist", which you can declare at the top of the script and set to whatever you like from the inspector or what have you.
This works perfectly thanks. This is what I was doing but somewhere I was going wrong.
Your answer
Follow this Question
Related Questions
Camera rotation around player while following. 6 Answers
C # script the enemy chases the player. 2 Answers
Adding a counter? 1 Answer
change script so enemy car gets destroyed when collided with player car 0 Answers
Help With Maze Pathfinding AI. 2 Answers