- Home /
How do I make my enemy stop moving towards me within a certain distance?
The enemy I made comes towards me and attacks me - how do I set it so it doesn't get within a certain distance with me?
var distance; var target : Transform;
var lookAtDistance = 15.0; var attackRange = 10.0; var moveSpeed = 5.0; var damping = 6.0; private var isItAttacking = false;
function Update ()
{
distance = Vector3.Distance(target.position, transform.position);
if(distance < lookAtDistance)
{
isItAttacking = false;
lookAt ();
}
if(distance < attackRange)
{
attack ();
}
}
function lookAt () { var rotation = Quaternion.LookRotation(target.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); }
function attack () { isItAttacking = true;
transform.Translate(Vector3.forward * moveSpeed *Time.deltaTime);
}
Answer by Griffo · Jan 20, 2013 at 01:03 PM
var standOffDistance : float = 2;
if((distance < attackRange) && (distance > standOffDistance))
{
attack ();
}
EDIT: It slows down when it gets close but it doesn't stop when I stop.
You also need to check if Translate parameter won't make the enemy surpass the standOffDistance, if this surpass, clamp a maximum value.
And how do I do that? Sorry, i'm fairly new to scripting.
It works for me -
#pragma strict
var distance : float;
var target : Transform;
var lookAtDistance : int = 15.0;
var attackRange : int = 10.0;
var standOffDistance : float = 2;
var moveSpeed : int = 5.0;
var damping : int = 6.0;
function Update ()
{
distance = Vector3.Distance(target.position, transform.position);
if(distance < lookAtDistance)
{
lookAt ();
}
if((distance < attackRange) && (distance > standOffDistance))
{
attack ();
}
}
function lookAt ()
{
var rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}
function attack ()
{
transform.Translate(Vector3.forward * moveSpeed *Time.deltaTime);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613091228im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Look at closer to player 1 Answer
Distance destroy object 3 Answers
How to make player stop a certain distance away from enemy? 1 Answer
SphereCastAll sees for miles 2 Answers
Check Between Enemy List 1 Answer