Last active
December 19, 2016 20:10
-
-
Save Gaweph/4cc5359a43d724a534ddc6efc82cc58d to your computer and use it in GitHub Desktop.
Unity3d Script to add mechanim animation to objects based on their movement between frames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Linq; | |
public class AnimationFromTransform : MonoBehaviour { | |
public float MinMovementAmount = 1; | |
public string MechanimMovementName = "Forward"; | |
private Animator _anim; | |
void Start () { | |
_prevPosition = Transform.position; | |
_anim = GetComponentsInChildren<Animator>().FirstOrDefault(); | |
if(_anim == null) | |
{ | |
_anim = GetComponent<Animator>(); | |
} | |
} | |
private Vector3 _prevPosition; | |
void Update () { | |
if (_anim != null) | |
{ | |
Vector3 vel = (Transform.position - _prevPosition) / Time.timeScale; | |
var movement = Mathf.Max(Mathf.Abs(vel.x), Mathf.Abs(vel.z)); | |
if (movement > 0f) | |
{ | |
movement = Mathf.Max(MinMovementAmount, movement); | |
} | |
_anim.SetFloat(MechanimMovementName, movement); | |
_prevPosition = Transform.position; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment