Skip to content

Instantly share code, notes, and snippets.

@Gaweph
Last active December 19, 2016 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gaweph/4cc5359a43d724a534ddc6efc82cc58d to your computer and use it in GitHub Desktop.
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
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