I’m new to Unity so this may sound quite trivial to others.
Basically, I’m attempting to create a small mine object that moves towards the player when he is within range and then explodes. Through some research and modifying, I found some coding that allowed me to make the mine wait until the player is within range and then charge towards him. When the Mine detects the player, the mine has a 5 second timer before it explodes/destroyed. My main issue is that the mine will destroy regardless of the distance between the Player and the Mine. Below is coding I’m using.
var start: Transform;
var end: Transform;
var target : Transform; //the enemy's target
var moveSpeed = 3; //move speed
var rotationSpeed = 3; //speed of turning
var enemydistance =3;
var enemy : Transform; //current transform data of this enemy
function Awake()
{
enemy = transform; //cache transform data for easy access/preformance
}
function Start()
{
target = GameObject.FindWithTag("Player").transform; //target the player
}
function Update ()
{
//Detect Distance between Player and Mine
if ( Vector3.Distance( enemy.position, (Vector3.Lerp(start.position, end.position,Time.time) )) < enemydistance ) {
//rotate to look at the player
enemy.rotation = Quaternion.Slerp(enemy.rotation,
Quaternion.LookRotation(target.position - enemy.position), rotationSpeed*Time.deltaTime);
//move towards the player
enemy.position += enemy.forward * moveSpeed * Time.deltaTime;
//Destroy Mine after 5 seconds
Destroy(gameObject,5) ;
}
}
Basically, its ignoring the If statement regarding the distance and just destroys it after 5 seconds. Where abouts did I stuff it up and what can I do to fix it?