- Home /
Having problem with Vector3.distance
Hi guys im having problem with the code below, on the console it written the distance does not exist in current context? Anyone know the solution?
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
public Transform target;
public int moveSpeed;
public int rotationSpeed;
float range = 10.0f;
float range2 = 10.0f;
float stop = 0.0f;
private Transform myTransform;
void Awake(){
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update () {
distance= Vector3.Distance(myTransform.position, target.position);
if (distance <= range2 && distance >= range){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
}
else if(distance <= range && distance > stop){
//move towards the player
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.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);
}
}
}
Answer by meat5000 · Oct 07, 2013 at 06:36 PM
Looks to me like you haven't declared distance variable at the start of your script.
Yeah, the simple solution to this is i just put a float to distance and it able to run but however this script is suppose make the enemy stop at a distance but apparently its not, anyone know why?
Yeah. Range and Range 2 are the same value.
if (distance <= range2 && distance >= range)
This basically says if (distance == range) if you analyze it.
Hitting an exact integer in a float value is not likely between frames.
Your answer
Follow this Question
Related Questions
Get x and y Distance between two Vectors 1 Answer
3 vector3 distance checks, only one works 1 Answer
Ambientlight by distance 1 Answer
GameObject's transform in Vector3 1 Answer