- Home /
Animation doesn't play when distant check is triggered
Another question from the user with the mental capacity of a wooden spoon.
I have this script here that's supposed to activate a animation for a modeled, rigged, textured, monster I made with unity. I added the animation and the script to the monster doing some box checking so it says on trigger. Thanks for reading and if there is a reputation system here please tell me so after posting your answer.
var distance;
var reach = 10.0;
function Update ()
{ if(distance < reach) { animation.Play ("Sprint");
} }
If you need to say something about the answers given use the comment box, you won't have to wait for moderation and that is how it works.
Answer by fafase · Aug 19, 2012 at 10:42 AM
You have two ways to check distance:
Using Vector
Using triggerBox
1-
var target:Transform;
var range :int;
function Start(){
target = GameObject.Find("PlayerOrElse").transform;
}
function Update(){
if(Vector3.Distance(transform.position, target.position)< range){
//Action
}
2-
Add a empty game object to your NPC, add a sphere collider to it and tick IsTrigger. On the main script, you could have:
PlayerScript.js
var inRange:boolean;
function Update(){
if(inRange){
//Action
}
}
the empty object has:
var script:PlayerScript;
function Start(){
script = gameObject.GetComponent(PlayerScript);
}
function OnTriggerEnter(other:Collider){
if(other.gameObject.tag=="Player")script.InRange=true;
}
function OnTriggerExit(other:Collider){
if(other.gameObject.tag=="Player")script.InRange=false;
}
The second approach will save some cycles since only a boolean is checked when the first one needs to perform the distance calculation, not that big a deal though but if you have a lot of this type of NPC, in the long run that could make a tiny difference.
Your answer
Follow this Question
Related Questions
URGENT: incorrect animation distance 0 Answers
How to measure the overall distance travelled? 1 Answer
Can I make animations snap to a frame? 1 Answer
Play an animation after entering a set distance won't work. 1 Answer
Problems with animation. 0 Answers