Skip to content

Instantly share code, notes, and snippets.

@garzaa
Forked from mnogue/ToonMotion.cs
Last active January 7, 2024 05:28
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 garzaa/59596a6836804338258ad53ff09cd0cb to your computer and use it in GitHub Desktop.
Save garzaa/59596a6836804338258ad53ff09cd0cb to your computer and use it in GitHub Desktop.
Split animations down into predefined fps
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ToonMotion : MonoBehaviour {
public int fps = 18;
public List<GameObject> ignoreGameobjects;
float lastUpdateTime = 0f;
bool forceUpdateThisFrame = false;
List<Snapshot> snapshots = new List<Snapshot>();
int i=0;
void Start() {
CreateTargetList(this.transform);
}
void CreateTargetList(Transform parent) {
if (parent == null) return;
int childrenCount = parent.childCount;
for (int i = 0; i < childrenCount; i++) {
Transform target = parent.GetChild(i);
// yeah this is slow. too bad, it runs once at startup
if (!ignoreGameobjects.Contains(target.gameObject)) {
snapshots.Add(new Snapshot(target));
}
CreateTargetList(target);
}
}
void LateUpdate() {
if (forceUpdateThisFrame || Time.unscaledTime - lastUpdateTime > 1f/this.fps) {
for (i=0; i<snapshots.Count; i++) {
snapshots[i].UpdateSelf();
}
this.lastUpdateTime = Time.unscaledTime;
forceUpdateThisFrame = false;
} else {
for (i=0; i<snapshots.Count; i++) {
snapshots[i].Maintain();
}
}
}
public void ForceUpdate() {
forceUpdateThisFrame = true;
}
private class Snapshot {
public Transform transform;
public Vector3 position;
public Quaternion rotation;
public Snapshot(Transform transform) {
this.transform = transform;
this.UpdateSelf();
}
public void UpdateSelf() {
position = transform.localPosition;
rotation = transform.localRotation;
}
public void Maintain() {
transform.localPosition = position;
transform.localRotation = rotation;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment