Now that your animated character is ready, you might want to coordinate some of her actions with her animation states. In this recipe, we will exemplify this by making the character throw an object whenever the appropriate animation clip reaches the right time. To do so, we will make use of Animation Events, which basically trigger a function from the animation clip's timeline. This feature, recently introduced to the Mecanim system, should feel familiar to those experienced with the Add Event feature of the classic Animation panel.
For this recipe, we have prepared a Unity Package named Throwing
, containing a basic scene that features an animated character and a prefab named EasterEgg. The package can be found inside the 1362_07_07
folder.
To make an animated character throw an Easter egg (!), follow these steps:
Throwing
Unity Package. Then, from the Project view, open the mecanimPlayground level.ThrowObject.cs.
using UnityEngine; using System.Collections; public class ThrowObject : MonoBehaviour { public GameObject prop; private GameObject proj; public Vector3 posOffset; public Vector3 force; public Transform hand; public float compensationYAngle = 0f; public void Prepare () { proj = Instantiate(prop, hand.position, hand.rotation) as GameObject; if(proj.GetComponent<Rigidbody>()) Destroy(proj.GetComponent<Rigidbody>()); proj.GetComponent<SphereCollider>().enabled = false; proj.name = "projectile"; proj.transform.parent = hand; proj.transform.localPosition = posOffset; proj.transform.localEulerAngles = Vector3.zero; } public void Throw () { Vector3 dir = transform.rotation.eulerAngles; dir.y += compensationYAngle; proj.transform.rotation = Quaternion.Euler(dir); proj.transform.parent = null; proj.GetComponent<SphereCollider>().enabled = true; Rigidbody rig = proj.AddComponent<Rigidbody>(); Collider projCollider = proj.GetComponent<Collider> (); Collider col = GetComponent<Collider> (); Physics.IgnoreCollision(projCollider, col); rig.AddRelativeForce(force); } }
0
; Y: 0.07
; Z: 0.04
. Finally, change Force to X: 0
; Y: 200
; Z: 500
.Prepare
. Close the window.Throw
. Close the window.Once the toss_grenade animation reaches the moments that we have set our Events to, the Prepare()
and throw()
functions are called. The former instantiates a prefab, now named projectile, into the character's hand (Projectile Offset values are used to fine-tune its position), also making it respect the character's hierarchy. Also, it disables the prefab's collider and destroys its Rigidbody
component, provided it has one. The latter function enables the projectile's collider, and adds a Rigidbody
component to it, making it independent from the character's hand. Finally, it adds a relative force to the projectile's Rigidbody
component, so it will behave as if thrown by the character. The Compensation YAngle can be used to adjust the direction of the grenade, if necessary.
3.133.141.219