I need to make a “Ghost” entity appear when it approach’s the player. its a simple follow AI but i want it to be invisible from the player until it gets within about 5m of the player and then appear, also i would like its audio emitter to change when it appears to signal it is close, but this is not important.
If i understand correctly, That can help you.
if(Vector3.Distance(Player.transform.position,ghost.transform.position)<=5)
{
ghost.GetComponent<MeshRenderer>().enable = true;
ghostAudio.volume = 5-Vector3.Distance(Player.transform.position,ghost.transform.position);
}
Without using physics, you can just compute distance, something like:
void Update() {
float distance = Vector3.Distance(player.transform.position, ghost.transform.position);
ghost.renderer.enabled = (distance < 5);
}
You could make some easy optimizations to the snippet above, or use the physics system. With physics, put a 5m radius trigger collider and rigidbody around the ghost, and a collider and rigidbody on the player (or vice-versa). If the ghost gets an OnTriggerEnter message, appear. If the ghost gets an OnTriggerExit message, disappear.
void OnTriggerEnter(Collider other) {
if (string.Equals(other.tag, "Player") {
renderer.enabled = true;
}
}
And similar for working with the audio component.
(Untested code since I’m not near Unity right now, but this should give you an idea).
hmmm i cant seem to get these to work, more likely my lack of knowledge with scripting, but one thing I’ve sorta noticed that might be a problem is that i dont have a mesh for the ghost as such, its more like a wisp thing with a particle emitter on it, so i should of said that i need to disable the particle emitter unless within range of the player. so would i be better off using a script like this?
var flame : GameObject;
function Start () {
flame.SetActive(false);
}
function OnTriggerEnter(){
flame.SetActive(true);
}
function OnTriggerExit(){
flame.SetActive(false);
}
if so can i modify this to apply the audio as well?
Thnaks for your help guys