- Home /
Animation delay until certain distance
I have two objects in scene/level, one ball and a man who is supposed to hit that ball.
I already made the animation and script to play it in Unity after key press.
But almost every time man's hand misses the ball.
My question : How can I delay animation (after I press the key) until the ball is on certain distace to the man ?
Answer by save · Jul 05, 2011 at 10:57 PM
For precise distances there's this handy tool.
var theDistance = Vector3.Distance(man.position, ball.position);
For not as precise but quicker calculated try this.
var sqrLen = (man.position - ball.position).sqrMagnitude;
Then you could for instance say:
private var ballDistance : float = 0.0;
var man : Transform;
var ball : Transform;
function Update () {
ballDistance = Vector3.Distance(man.position, ball.position); //Calculate distance
if (Input.GetKeyDown(KeyCode.S)) {
swing(); //Drop to a coroutine
}
}
function swing () {
while ( ballDistance>0.5 ) yield; //Wait for the right moment
animation.Play(); //Call your animation from here
}
(Not tested)
You could also, instead of calculating distance (which does take some CPU-cycles), work with a collider set as a trigger. When the key is pressed set a boolean to true and when the ball enters the collider check that boolean, then fire the animation.
Good answer, needed a few changes but generaly good.Thank you!
Glad it worked out, next time post a little bit of code so you wont have to restructure any code samples you get from us - makes it easier for both parts. ;-)
Answer by Daemon0x0 · Dec 12, 2012 at 06:46 PM
Hi, maybe just try to use a collider at bone and handle direct this bone. I made somethink similar and I direct rotated the knee and hip bones when the ball touched the collider at toeBone. It worked fine.
Answer by Daemon0x0 · Dec 12, 2012 at 06:46 PM
Hi, maybe just try to use a collider at bone and handle direct this bone. I made somethink similar and I direct rotated the knee and hip bones when the ball touched the collider at toeBone. It worked fine.