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 ?

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.

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.

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.