Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Playing character animations with triggers.

Discussion in 'Animation' started by TheBoredMan5, May 12, 2014.

  1. TheBoredMan5

    TheBoredMan5

    Joined:
    Mar 16, 2013
    Posts:
    9
    Hi, I'm trying to make some type of system that when my character runs through a collider or trigger my character will do an animation. Like he will jump or something.
    I want to be able to put a collider set to "is trigger" in front of a wall, and then when my character runs through the trigger. He will play an animation that allows him to climb over the wall.
    Would anyone know how to do this? or be able to provide any script? Thanks.
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,625
    Sounds like you already have most of it thought out. Yes, you can attach a script to the trigger that implements OnTriggerEnter().

    Here's a rough sketch. I'm not near Unity right now, so this is untested.
    Code (csharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class AnimationTrigger : MonoBehaviour {
    5.  
    6.     public string animationTrigger;
    7.  
    8.     void OnTriggerEnter(Collider other) {
    9.         // Align the object with the direction of the trigger:
    10.         other.transform.rotation = transform.rotation;
    11.  
    12.         // Trigger the Mecanim animation:
    13.         Animator animator = other.GetComponent<Animator>();
    14.         if (animation != null) animator.SetTrigger(animationTrigger);
    15.     }
    16. }
    17.  
    Some notes:
    • The implementation above uses Mecanim. Set up a trigger that plays the climbing animation, and set the animationTrigger property to the name of that animation. For Legacy, you'd use animation.CrossFade() instead, and you'd have to script the motion yourself.
    • Align the trigger to the direction that the animation should play. The script aligns the player's rotation to the trigger. This way, if the player enters at a slight angle, he still climbs straight up the wall.
    • You could get fancier with Mecanim target matching, smoothing to the trigger's rotation, and more. You could also check to make sure that the collider other is actually allowed to climb the wall (for example, string.Equals(other.tag, "Player")).