- Home /
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));
print("forward");
}
else{
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
print("backwards");
}
}
function OnCollisionEnter(collision : Collision)
{
Destroy(gameObject);
}
So what am I doing wrong...?
:(
Thanks in advance guys!
well what is not working? It's hard to guess - It'd be easier if we new whether you get any errors in the console etc. :)
Sorry for being so vague!! It appears to just go straight to the else statement. The enemy is spawn about a good 500(not sure what measurement unity uses!!) in front if the player and doesn't bother approaching at all :S
I would perhaps try debugging and narrowing it down further - for example check the distanceToPlayer variable's value using:
Debug.Log("Distance to player: "+distanceToPlayer);
It's only a guess but it's good to just check that all variables are fine and not causing any trouble :D
You could take off the var player = GameObject.Find("Sphere(Clone)"); which looks kinda weird to me, and simply drag your player object to the slot in the inspector. transform.LookAt (player); also.
var player = GameObject.Find("Sphere(Clone)");
looked a bit weird to me at first too, but it shouldn't cause any problems since it is searching for the object "Sphere(Clone)" and the brackets are just part of the name, I think.
Answer by kidshenlong · Mar 27, 2012 at 02:43 PM
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 :)