- Home /
How do I use RayCasting to play a sound when my player is close to an enemy
I want to have a sound play when my player is close to an enemy AND only when that enemy is visible ( i'll be using renderer.isVisible ) If my enemy comes up behind me and i turn around a sound doesn't play . I tried used trigger zones but i couldn't get that to work, and i'm not very familiar with raycasting so help is appreciated. (could it be possible to have a trigger on the player so when the enemy entered it and was visible it played? how could I refer the enemy to the render.isVisible)
my current script function OnTriggerEnter(other : Collider){ if(other.gameObject.tag == "Player" && renderer.isVisible){ audio.Play(); } }
FOR ANYONE INTERESTED FINAL SCRIPT IS
function OnTriggerStay(other : Collider){
if(other.gameObject.tag == "Player" && renderer.isVisible && !audio.isPlaying){
audio.Play(); }}
If by 'trigger zones' you mean using a Collider with 'istrigger' set, that's the easiest, so I would be interested in what you did there and why that didn't work for you.
function OnTriggerEnter(other : Collider){
if(other.gameObject.tag == "Player" && renderer.isVisible){
audio.Play();
}
}
the sound plays if i'm looking at him and if i walk into the zone, however I want it to play if he comes up behind me and I turn around. Sorry if i explained it badly ;o
Answer by brandonetter · Aug 14, 2013 at 06:13 PM
Ah, I haven't tested this but have you tried changing "OnTriggerEnter" to "OnTriggerStay"? I think your issue is that your 'Player' enters the collider while the renderer isn't visible, and when the renderer IS visible you aren't entering the collider, you're already in it.
function OnTriggerStay(other : Collider){
if(other.gameObject.tag == "Player" && renderer.isVisible){
audio.Play();
}
}
Ahh this seems to be working a lot better now thank you =D <3, do you know the script to not play audio if it's already playing?
Oh... it it just continuing to play over and over? Ha sorry about that. try this-
http://docs.unity3d.com/Documentation/ScriptReference/AudioSource-isPlaying.html
Yeah my fault really haha =D basically it just kept starting the clip again half way through if I moved. Thank you very much for your help =D
Oh, and is there some kind of horror game-jam going on? So many questions about this kind of thing today. Best of luck btw!!
xD well unity is a very popular engine for horror after slender, I always wanted to make games and this is my first but i really have fun with horror especially =D