How can I make an enemy follow a character from a distance like in Slenderman.
I have tried, but I can’t seem to get it right.
What have you tried? We can only give specific guidance if you ask a specific question.
I had a little help looking on the internet. it was supposed to follow me when i got in a certain range. Here is the script:
var target : Transform; //the enemy’s target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var range : float=10f;
var range2 : float=10f;
var stop : float=0;
var myTransform : Transform; //current transform data of this enemy
function Awake()
{
myTransform = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag(“Player”).transform; //target the player
}
function Update () {
//rotate to look at the player
var distance = Vector3.Distance(myTransform.position, target.position);
if (distance<=range2 && distance>=range){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeedTime.deltaTime);
}
else if(distance<=range && distance>stop){
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeedTime.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
else if (distance<=stop) {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
}
First. Use code tags.
Second. I would suggest you using Navmesh. It detects obstacles and avoids them as long they’re not moving.
There you can set a distance between player and himself at which he can stop.
Also, Navmesh is good for terrains at different levels.
Shouldn’t this post be in Scripting?
Yes it should be. Seems he is posting a lot of questions in this section and not the correct ones…
Or the Getting Started section.
if (distance<=range2 && distance>=range)
So… is it likely that your distance to the enemy will simultaneously be less than 10 and greater than 10 at the same time? Also, what are the chances that you will ever be exactly 10.0 units away from the enemy?
Is he moving at all? What’s actually happening?
Yeah, this is an example of where better variable names would really help. Replace range with minRange and range2 with maxRange, and suddenly the code’s meaning becomes more clear. With obvious variable names, the OP would have picked better values for the variables. (not 10 for both) I’d also recommend changing the variable name stop to stopDistance.