Enemy Approaching player and then stopping in front??

Hey guys need a quick bit of help. My game is a star fox clone essentally so maybe that’ll give you an idea of what I’m trying to do. I was messing around with some code. I wanted the enemy to approach the player and when he gets within the “safe distance” to turn in the opposite direction and match the players speed and then later start attackign but one thing at a time!

var player:GameObject;

var safeDistance = 20; //How close the player can get

public var speed =10;

function Update()


var player = GameObject.Find(“Sphere(Clone)”);

//transform.LookAt (player.transform); //you look at player with this

//write other codes here

var distanceToPlayer = Vector3.Distance(this.transform.position, player.transform.position);

// this checks to see if the player is too close then runs the fire function

if(distanceToPlayer <= safeDistance){

transform.Translate (Vector3(0,0,2));




transform.Translate (Vector3(0,0,Random.Range(-1,-10))); //moves with speed in local z and you are looking toward him so you move toward the player




function OnCollisionEnter(collision : Collision)




So what am I doing wrong…?


Thanks in advance guys!

Think I’ve figured it out! Thanks everyone but specifically merry-christmas I would’ve of discovered the issue if hadn’t debugged.

Basically the object was moving too fast. 20 was too small a unit to use as it would count down and fly past me before it could even check if the enemy was close. the problem is when it flew past the player the distance would start building up again so it’d never detect being that close to me. Bumping safeDistance up to a 100 fixed the issue.

I hope that made sense.

Thanks for the input guys :slight_smile: