This commit is contained in:
左右看
2023-06-29 17:00:52 +08:00
1469 changed files with 1264652 additions and 249 deletions
-8
View File
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: a8c00ee8c4666954cb9915799f0248d2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
-9
View File
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 47bf04154c11c5e45b94b1aec2c0baf6
folderAsset: yes
timeCreated: 1516620867
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 8d2079bf8fd63d640a121f8fea6f5c5f
folderAsset: yes
timeCreated: 1516620916
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,498 +0,0 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Playables;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace RootMotion
{
/// <summary>
/// Base class for animation bakers, handles timing, keyframing and saving AnimationClips.
/// </summary>
[HelpURL("http://www.root-motion.com/finalikdox/html/page3.html")]
[AddComponentMenu("Scripts/RootMotion/Baker")]
public abstract class Baker : MonoBehaviour
{
// Open the User Manual URL
[ContextMenu("User Manual")]
void OpenUserManual()
{
Application.OpenURL("http://www.root-motion.com/finalikdox/html/page3.html");
}
// Open the Script Reference URL
[ContextMenu("Scrpt Reference")]
void OpenScriptReference()
{
Application.OpenURL("http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_baker.html");
}
// Link to the Final IK Google Group
[ContextMenu("Support Group")]
void SupportGroup()
{
Application.OpenURL("https://groups.google.com/forum/#!forum/final-ik");
}
// Link to the Final IK Asset Store thread in the Unity Community
[ContextMenu("Asset Store Thread")]
void ASThread()
{
Application.OpenURL("http://forum.unity3d.com/threads/final-ik-full-body-ik-aim-look-at-fabrik-ccd-ik-1-0-released.222685/");
}
[System.Serializable]
public enum Mode
{
AnimationClips = 0,
AnimationStates = 1,
PlayableDirector = 2,
Realtime = 3
}
/// <summary>
/// In AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
/// </summary>
[Tooltip("In AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.")]
[Range(1, 90)] public int frameRate = 30;
/// <summary>
/// Maximum allowed error for keyframe reduction.
/// </summary>
[Tooltip("Maximum allowed error for keyframe reduction.")]
[Range(0f, 0.1f)] public float keyReductionError = 0.01f;
/// <summary>
/// AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
/// </summary>
[Tooltip("AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. " +
"AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. " +
"PlayableDirector mode bakes a Timeline. " +
"Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.")]
public Mode mode;
/// <summary>
/// AnimationClips to bake.
/// </summary>
[Tooltip("AnimationClips to bake.")]
public AnimationClip[] animationClips = new AnimationClip[0];
/// <summary>
/// The name of the AnimationStates to bake (must be on the base layer) in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
/// </summary>
[Tooltip("The name of the AnimationStates to bake (must be on the base layer) in the Animator above (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).")]
public string[] animationStates = new string[0];
/// <summary>
/// Sets the baked animation clip to loop time and matches the last frame keys with the first. Note that if you are overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
/// </summary>
[Tooltip("Sets the baked animation clip to loop time and matches the last frame keys with the first. Note that when overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.")]
public bool loop = true;
/// <summary>
/// The folder to save the baked AnimationClips to.
/// </summary>
[Tooltip("The folder to save the baked AnimationClips to.")]
public string saveToFolder = "Assets";
/// <summary>
/// String that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
/// </summary>
[Tooltip("String that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.")]
public string appendName = "_Baked";
/// <summary>
/// Name of the created AnimationClip file.
/// </summary>
[Tooltip("Name of the created AnimationClip file.")]
public string saveName = "Baked Clip";
public bool isBaking { get; private set; }
public float bakingProgress { get; private set; }
[SerializeField] [HideInInspector] public Animator animator;
[SerializeField] [HideInInspector] public PlayableDirector director;
protected abstract Transform GetCharacterRoot();
protected abstract void OnStartBaking();
protected abstract void OnSetLoopFrame(float time);
protected abstract void OnSetCurves(ref AnimationClip clip);
protected abstract void OnSetKeyframes(float time, bool lastFrame);
protected float clipLength { get; private set; }
#if UNITY_EDITOR
private AnimationClip[] bakedClips = new AnimationClip[0];
private AnimatorStateInfo currentClipStateInfo;
private int currentClipIndex;
private float startBakingTime;
private float nextKeyframeTime;
private bool firstFrame;
private int clipFrames;
private int clipFrameNo;
private bool setKeyframes;
private float currentClipTime;
private float clipFrameInterval;
private const bool setLoopFrame = true; // Makes sure first and last keyframes in the baked clip match up if baking a looping clip.
#endif
// Start baking an animation state, clip or timeline, also called for each next clip in the baking array
public void BakeClip()
{
#if UNITY_EDITOR
switch (mode)
{
case Mode.AnimationClips:
AnimationClipSettings originalSettings = AnimationUtility.GetAnimationClipSettings(animationClips[currentClipIndex]);
loop = originalSettings.loopTime;
break;
}
StartBaking();
#endif
}
public void StartBaking()
{
#if UNITY_EDITOR
isBaking = true;
nextKeyframeTime = 0f;
bakingProgress = 0f;
clipFrameNo = 0;
if (bakedClips.Length == 0)
{
switch (mode)
{
case Mode.AnimationClips:
bakedClips = new AnimationClip[animationClips.Length];
break;
case Mode.AnimationStates:
bakedClips = new AnimationClip[animationStates.Length];
break;
default:
bakedClips = new AnimationClip[1];
break;
}
}
OnStartBaking();
firstFrame = true;
#endif
}
public void StopBaking()
{
#if UNITY_EDITOR
if (!isBaking) return;
if (mode != Mode.Realtime && loop && setLoopFrame)
{
OnSetLoopFrame(clipLength);
}
bakedClips[currentClipIndex] = new AnimationClip();
bakedClips[currentClipIndex].frameRate = frameRate;
OnSetCurves(ref bakedClips[currentClipIndex]);
bakedClips[currentClipIndex].EnsureQuaternionContinuity();
if (mode == Mode.Realtime)
{
isBaking = false;
SaveClips();
}
#endif
}
#if UNITY_EDITOR
[ContextMenu("Find Animation States")]
public void FindAnimationStates()
{
animator = GetComponent<Animator>();
if (animator == null)
{
Debug.LogError("No Animator found on Baker GameObject. Can not find animation states.");
return;
}
if (animator.runtimeAnimatorController == null)
{
Debug.LogError("Animator does not have a valid Controller. Can not find animation states.");
return;
}
var clips = animator.runtimeAnimatorController.animationClips;
animationStates = new string[clips.Length];
for (int i = 0; i < clips.Length; i++)
{
animationStates[i] = clips[i].name;
}
}
void Update()
{
// Baking procedure
if (isBaking)
{
if (mode != Mode.Realtime)
{
if (firstFrame)
{
transform.position = Vector3.zero;
transform.rotation = Quaternion.identity;
GetCharacterRoot().position = Vector3.zero;
GetCharacterRoot().rotation = Quaternion.identity;
StartAnimationUpdate();
currentClipTime = 0f;
firstFrame = false;
}
switch (mode)
{
case Mode.AnimationClips:
clipLength = animationClips[currentClipIndex].length;
bakingProgress = currentClipTime / clipLength;
break;
case Mode.AnimationStates:
currentClipStateInfo = animator.GetCurrentAnimatorStateInfo(0);
bakingProgress = currentClipStateInfo.normalizedTime;
if (currentClipStateInfo.speed <= 0f)
{
Debug.LogError("Baker can not bake a clip with 0 speed.");
return;
}
clipLength = currentClipStateInfo.length / currentClipStateInfo.speed / animator.speed;
break;
case Mode.PlayableDirector:
clipLength = (float)director.duration;
bakingProgress = (float)director.time / clipLength;
break;
}
clipFrames = (int)(clipLength * (frameRate));
clipFrameInterval = clipLength / (float)(clipFrames);
setKeyframes = true;
// Stop clip baking if the clip is finished, start baking the next clip if possible
if (clipFrameNo > clipFrames)
{
StopBaking();
currentClipIndex++;
if (currentClipIndex >= bakedClips.Length)
{
currentClipIndex = 0;
StopAnimationUpdate();
isBaking = false;
SaveClips();
return;
}
else
{
BakeClip();
setKeyframes = false;
}
}
if (!firstFrame) AnimationUpdate();
}
}
}
void LateUpdate()
{
if (!isBaking) return;
if (mode != Mode.Realtime)
{
if (setKeyframes)
{
OnSetKeyframes(clipFrameNo * clipFrameInterval, clipFrameNo >= clipFrames);
clipFrameNo++;
setKeyframes = false;
}
}
else
{
if (firstFrame)
{
startBakingTime = Time.time;
firstFrame = false;
}
if (Time.time < nextKeyframeTime) return;
OnSetKeyframes(Time.time - startBakingTime, false);
nextKeyframeTime = Time.time + (1f / (float)frameRate);
}
}
private void StartAnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (!AnimationMode.InAnimationMode()) AnimationMode.StartAnimationMode();
AnimationMode.BeginSampling();
AnimationMode.SampleAnimationClip(gameObject, animationClips[currentClipIndex], 0f);
AnimationMode.EndSampling();
break;
case Mode.AnimationStates:
animator.enabled = false;
animator.Play(animationStates[currentClipIndex], 0, 0f);
break;
case Mode.PlayableDirector:
director.enabled = false;
director.time = 0f;
director.Evaluate();
break;
}
}
private void StopAnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (AnimationMode.InAnimationMode()) AnimationMode.StopAnimationMode();
break;
case Mode.AnimationStates:
animator.enabled = true;
break;
case Mode.PlayableDirector:
director.enabled = true;
break;
}
}
private void AnimationUpdate()
{
switch (mode)
{
case Mode.AnimationClips:
if (!AnimationMode.InAnimationMode()) AnimationMode.StartAnimationMode();
AnimationMode.BeginSampling();
AnimationMode.SampleAnimationClip(gameObject, animationClips[currentClipIndex], currentClipTime);
AnimationMode.EndSampling();
currentClipTime += clipFrameInterval;
break;
case Mode.AnimationStates:
animator.Update(clipFrameInterval);
break;
case Mode.PlayableDirector:
director.time = currentClipTime;
director.Evaluate();
currentClipTime += clipFrameInterval;
break;
}
}
public void SaveClips()
{
var clips = GetBakedClips();
AnimationClip savedClip = null;
for (int i = 0; i < clips.Length; i++)
{
string path = GetFullPath(i);
switch (mode)
{
case Baker.Mode.Realtime: break;
case Baker.Mode.AnimationClips:
AnimationClipSettings originalSettings = AnimationUtility.GetAnimationClipSettings(animationClips[i]);
SetClipSettings(clips[i], originalSettings);
AnimationUtility.SetAnimationClipSettings(clips[i], originalSettings);
break;
default:
AnimationClipSettings settings = AnimationUtility.GetAnimationClipSettings(clips[i]);
settings.loopTime = loop;
SetClipSettings(clips[i], settings);
AnimationUtility.SetAnimationClipSettings(clips[i], settings);
break;
}
var existing = AssetDatabase.LoadAssetAtPath(path, typeof(AnimationClip)) as AnimationClip;
if (existing != null)
{
// Overwrite with existing settings
AnimationClipSettings existingSettings = AnimationUtility.GetAnimationClipSettings(existing);
AnimationUtility.SetAnimationClipSettings(clips[i], existingSettings);
EditorUtility.CopySerialized(clips[i], existing);
}
else
{
// Create new asset
AssetDatabase.CreateAsset(clips[i], path);
}
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
savedClip = AssetDatabase.LoadAssetAtPath(path, typeof(AnimationClip)) as AnimationClip;
Debug.Log(path + " successfully baked.");
}
Selection.activeObject = savedClip;
ClearBakedClips();
}
protected virtual void SetClipSettings(AnimationClip clip, AnimationClipSettings settings) {}
private string GetFullPath(int clipIndex)
{
switch (mode)
{
case Baker.Mode.AnimationClips:
return saveToFolder + "/" + animationClips[clipIndex].name + appendName + ".anim";
case Baker.Mode.AnimationStates:
return saveToFolder + "/" + animationStates[clipIndex] + appendName + ".anim";
case Baker.Mode.PlayableDirector:
return saveToFolder + "/" + saveName + ".anim";
default:
return saveToFolder + "/" + saveName + ".anim";
}
}
private AnimationClip[] GetBakedClips()
{
return bakedClips;
}
private void ClearBakedClips()
{
bakedClips = new AnimationClip[0];
}
#endif
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: ab14efce3fefe4f4982f0fa6911d0cd4
timeCreated: 1516617114
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,134 +0,0 @@
using UnityEngine;
using System.Collections;
using System;
namespace RootMotion
{
/// <summary>
/// Baker for Generic/Legacy animation.
/// </summary>
public class GenericBaker : Baker
{
/// <summary>
/// If true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.
/// </summary>
[Tooltip("If true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.")]
public bool markAsLegacy;
/// <summary>
/// Root Transform of the hierarchy to bake.
/// </summary>
[Tooltip("Root Transform of the hierarchy to bake.")]
public Transform root;
/// <summary>
/// Root Node used for root motion.
/// </summary>
[Tooltip("Root Node used for root motion.")]
public Transform rootNode;
/// <summary>
/// List of Transforms to ignore, rotation curves will not be baked for these Transforms.
/// </summary>
[Tooltip("List of Transforms to ignore, rotation curves will not be baked for these Transforms.")]
public Transform[] ignoreList;
/// <summary>
/// LocalPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.
/// </summary>
[Tooltip("LocalPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.")]
public Transform[] bakePositionList;
private BakerTransform[] children = new BakerTransform[0];
private BakerTransform rootChild;
private int rootChildIndex = -1;
void Awake()
{
// Find all the child Transforms of the Animator
Transform[] childrenAndRoot = (Transform[])root.GetComponentsInChildren<Transform>();
children = new BakerTransform[0];
// Exlude the ignore list, construct the children array
for (int i = 0; i < childrenAndRoot.Length; i++)
{
if (!IsIgnored(childrenAndRoot[i]))
{
Array.Resize(ref children, children.Length + 1);
bool isRootNode = childrenAndRoot[i] == rootNode;
if (isRootNode) rootChildIndex = children.Length - 1;
children[children.Length - 1] = new BakerTransform(childrenAndRoot[i], root, BakePosition(childrenAndRoot[i]), isRootNode);
}
}
}
protected override Transform GetCharacterRoot()
{
return root;
}
protected override void OnStartBaking()
{
for (int i = 0; i < children.Length; i++)
{
children[i].Reset();
if (i == rootChildIndex) children[i].SetRelativeSpace(root.position, root.rotation);
}
}
protected override void OnSetLoopFrame(float time)
{
// TODO Change to SetLoopFrame like in HumanoidBaker
for (int i = 0; i < children.Length; i++) children[i].AddLoopFrame(time);
}
protected override void OnSetCurves(ref AnimationClip clip)
{
// TODO Length Multiplier
for (int i = 0; i < children.Length; i++) children[i].SetCurves(ref clip);
}
protected override void OnSetKeyframes(float time, bool lastFrame)
{
for (int i = 0; i < children.Length; i++) children[i].SetKeyframes(time);
}
// Is the specified Transform in the ignore list?
private bool IsIgnored(Transform t)
{
for (int i = 0; i < ignoreList.Length; i++)
{
if (t == ignoreList[i]) return true;
}
return false;
}
// Should we record the localPosition channels of the Transform?
private bool BakePosition(Transform t)
{
for (int i = 0; i < bakePositionList.Length; i++)
{
if (t == bakePositionList[i]) return true;
}
return false;
}
#if UNITY_EDITOR
protected override void SetClipSettings(AnimationClip clip, UnityEditor.AnimationClipSettings settings)
{
clip.legacy = markAsLegacy;
if (mode != Baker.Mode.AnimationClips)
{
clip.wrapMode = loop ? WrapMode.Loop : WrapMode.Default;
}
}
#endif
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 27b32efee52144c4e934e6c3272ceb2c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 10180
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: e468ef7e80a87f94588b5eeb3a423b91
folderAsset: yes
timeCreated: 1516621025
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,90 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
namespace RootMotion
{
public class TQ
{
public TQ(Vector3 translation, Quaternion rotation)
{
t = translation;
q = rotation;
}
public Vector3 t;
public Quaternion q;
}
/*
Written with the kind help of the one commonly known as Mecanim-Dev.
*/
public class AvatarUtility
{
public static Quaternion GetPostRotation(Avatar avatar, AvatarIKGoal avatarIKGoal)
{
int humanId = (int)HumanIDFromAvatarIKGoal(avatarIKGoal);
if (humanId == (int)HumanBodyBones.LastBone) throw new InvalidOperationException("Invalid human id.");
MethodInfo methodGetPostRotation = typeof(Avatar).GetMethod("GetPostRotation", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetPostRotation == null) throw new InvalidOperationException("Cannot find GetPostRotation method.");
return (Quaternion)methodGetPostRotation.Invoke(avatar, new object[] { humanId });
}
/// <summary>
/// Get IK position and rotation for foot/hand bone position/rotation.
/// </summary>
public static TQ GetIKGoalTQ(Avatar avatar, float humanScale, AvatarIKGoal avatarIKGoal, TQ bodyPositionRotation, TQ boneTQ)
{
int humanId = (int)HumanIDFromAvatarIKGoal(avatarIKGoal);
if (humanId == (int)HumanBodyBones.LastBone) throw new InvalidOperationException("Invalid human id.");
MethodInfo methodGetAxisLength = typeof(Avatar).GetMethod("GetAxisLength", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetAxisLength == null) throw new InvalidOperationException("Cannot find GetAxisLength method.");
MethodInfo methodGetPostRotation = typeof(Avatar).GetMethod("GetPostRotation", BindingFlags.Instance | BindingFlags.NonPublic);
if (methodGetPostRotation == null) throw new InvalidOperationException("Cannot find GetPostRotation method.");
Quaternion postRotation = (Quaternion)methodGetPostRotation.Invoke(avatar, new object[] { humanId });
var goalTQ = new TQ(boneTQ.t, boneTQ.q * postRotation);
if (avatarIKGoal == AvatarIKGoal.LeftFoot || avatarIKGoal == AvatarIKGoal.RightFoot)
{
// Here you could use animator.leftFeetBottomHeight or animator.rightFeetBottomHeight rather than GetAxisLenght
// Both are equivalent but GetAxisLength is the generic way and work for all human bone
float axislength = (float)methodGetAxisLength.Invoke(avatar, new object[] { humanId });
Vector3 footBottom = new Vector3(axislength, 0, 0);
goalTQ.t += (goalTQ.q * footBottom);
}
// IK goal are in avatar body local space
Quaternion invRootQ = Quaternion.Inverse(bodyPositionRotation.q);
goalTQ.t = invRootQ * (goalTQ.t - bodyPositionRotation.t);
goalTQ.q = invRootQ * goalTQ.q;
goalTQ.t /= humanScale;
goalTQ.q = Quaternion.LookRotation(goalTQ.q * Vector3.forward, goalTQ.q * Vector3.up);
return goalTQ;
}
public static HumanBodyBones HumanIDFromAvatarIKGoal(AvatarIKGoal avatarIKGoal)
{
HumanBodyBones humanId = HumanBodyBones.LastBone;
switch (avatarIKGoal)
{
case AvatarIKGoal.LeftFoot: humanId = HumanBodyBones.LeftFoot; break;
case AvatarIKGoal.RightFoot: humanId = HumanBodyBones.RightFoot; break;
case AvatarIKGoal.LeftHand: humanId = HumanBodyBones.LeftHand; break;
case AvatarIKGoal.RightHand: humanId = HumanBodyBones.RightHand; break;
}
return humanId;
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 2f9e403f0f8255c42b90254abc55f528
timeCreated: 1516435305
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,571 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion
{
public static class BakerUtilities
{
public static void ReduceKeyframes(AnimationCurve curve, float maxError)
{
if (maxError <= 0f) return;
curve.keys = GetReducedKeyframes(curve, maxError);
// TODO Flatten outTangent for keys that have the next key and testAfter sampled to the same value in the original clip. Same thing for the inTangent
}
public static Keyframe[] GetReducedKeyframes(AnimationCurve curve, float maxError)
{
Keyframe[] keys = curve.keys;
int i = 1;
while (i < keys.Length - 1 && keys.Length > 2)
{
Keyframe[] testKeys = new Keyframe[keys.Length - 1];
int c = 0;
for (int n = 0; n < keys.Length; n++)
{
if (i != n)
{
testKeys[c] = new Keyframe(keys[n].time, keys[n].value, keys[n].inTangent, keys[n].outTangent);
c++;
}
}
AnimationCurve testCurve = new AnimationCurve();
testCurve.keys = testKeys;
float test0 = Mathf.Abs(testCurve.Evaluate(keys[i].time) - keys[i].value);
float beforeTime = keys[i].time + (keys[i - 1].time - keys[i].time) * 0.5f;
float afterTime = keys[i].time + (keys[i + 1].time - keys[i].time) * 0.5f;
float testBefore = Mathf.Abs(testCurve.Evaluate(beforeTime) - curve.Evaluate(beforeTime));
float testAfter = Mathf.Abs(testCurve.Evaluate(afterTime) - curve.Evaluate(afterTime));
if (test0 < maxError && testBefore < maxError && testAfter < maxError)
{
keys = testKeys;
}
else
{
i++;
}
}
return keys;
}
public static void SetLoopFrame(float time, AnimationCurve curve)
{
Keyframe[] keys = curve.keys;
keys[keys.Length - 1].value = keys[0].value;
float inTangent = Mathf.Lerp(keys[0].inTangent, keys[keys.Length - 1].inTangent, 0.5f);
keys[0].inTangent = inTangent;
keys[keys.Length - 1].inTangent = inTangent;
float outTangent = Mathf.Lerp(keys[0].outTangent, keys[keys.Length - 1].outTangent, 0.5f);
keys[0].outTangent = outTangent;
keys[keys.Length - 1].outTangent = outTangent;
keys[keys.Length - 1].time = time;
curve.keys = keys;
}
public static void SetTangentMode(AnimationCurve curve)
{
#if UNITY_EDITOR
if (curve.length < 2) return;
for (int i = 1; i < curve.length - 1; i++)
{
UnityEditor.AnimationUtility.SetKeyLeftTangentMode(curve, i, UnityEditor.AnimationUtility.TangentMode.ClampedAuto);
UnityEditor.AnimationUtility.SetKeyRightTangentMode(curve, i, UnityEditor.AnimationUtility.TangentMode.ClampedAuto);
}
#endif
}
// Realigns quaternion keys to ensure shortest interpolation paths.
public static Quaternion EnsureQuaternionContinuity(Quaternion lastQ, Quaternion q)
{
Quaternion flipped = new Quaternion(-q.x, -q.y, -q.z, -q.w);
Quaternion midQ = new Quaternion(
Mathf.Lerp(lastQ.x, q.x, 0.5f),
Mathf.Lerp(lastQ.y, q.y, 0.5f),
Mathf.Lerp(lastQ.z, q.z, 0.5f),
Mathf.Lerp(lastQ.w, q.w, 0.5f)
);
Quaternion midQFlipped = new Quaternion(
Mathf.Lerp(lastQ.x, flipped.x, 0.5f),
Mathf.Lerp(lastQ.y, flipped.y, 0.5f),
Mathf.Lerp(lastQ.z, flipped.z, 0.5f),
Mathf.Lerp(lastQ.w, flipped.w, 0.5f)
);
float angle = Quaternion.Angle(lastQ, midQ);
float angleFlipped = Quaternion.Angle(lastQ, midQFlipped);
return angleFlipped < angle ? flipped : q;
}
}
//Manages the Animation Curves for Humanoid Q/T channels.
[System.Serializable]
public class BakerHumanoidQT
{
private Transform transform;
private string Qx, Qy, Qz, Qw;
private string Tx, Ty, Tz;
// Animation curves for each channel of the Transform
public AnimationCurve rotX, rotY, rotZ, rotW;
public AnimationCurve posX, posY, posZ;
private AvatarIKGoal goal;
private Quaternion lastQ;
private bool lastQSet;
// The custom constructor
public BakerHumanoidQT(string name)
{
Qx = name + "Q.x";
Qy = name + "Q.y";
Qz = name + "Q.z";
Qw = name + "Q.w";
Tx = name + "T.x";
Ty = name + "T.y";
Tz = name + "T.z";
Reset();
}
public BakerHumanoidQT(Transform transform, AvatarIKGoal goal, string name)
{
this.transform = transform;
this.goal = goal;
Qx = name + "Q.x";
Qy = name + "Q.y";
Qz = name + "Q.z";
Qw = name + "Q.w";
Tx = name + "T.x";
Ty = name + "T.y";
Tz = name + "T.z";
Reset();
}
// Clear all curves
public void Reset()
{
rotX = new AnimationCurve();
rotY = new AnimationCurve();
rotZ = new AnimationCurve();
rotW = new AnimationCurve();
posX = new AnimationCurve();
posY = new AnimationCurve();
posZ = new AnimationCurve();
lastQ = Quaternion.identity;
lastQSet = false;
}
public void SetIKKeyframes(float time, Avatar avatar, float humanScale, Vector3 bodyPosition, Quaternion bodyRotation)
{
// TODO Use character scale
TQ IKTQ = AvatarUtility.GetIKGoalTQ(avatar, humanScale, goal, new TQ(bodyPosition, bodyRotation), new TQ(transform.position, transform.rotation));
Quaternion rot = IKTQ.q;
if (lastQSet) rot = BakerUtilities.EnsureQuaternionContinuity(lastQ, IKTQ.q);
//rot.Normalize();
lastQ = rot;
lastQSet = true;
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
Vector3 pos = IKTQ.t;
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
public void SetKeyframes(float time, Vector3 pos, Quaternion rot)
{
// Rotation flipping already prevented in HumanoidBaker.UpdateHumanPose().
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
public void MoveLastKeyframes(float time)
{
MoveLastKeyframe(time, rotX);
MoveLastKeyframe(time, rotY);
MoveLastKeyframe(time, rotZ);
MoveLastKeyframe(time, rotW);
MoveLastKeyframe(time, posX);
MoveLastKeyframe(time, posY);
MoveLastKeyframe(time, posZ);
}
// Add a copy of the first frame to the specified time
public void SetLoopFrame(float time)
{
BakerUtilities.SetLoopFrame(time, rotX);
BakerUtilities.SetLoopFrame(time, rotY);
BakerUtilities.SetLoopFrame(time, rotZ);
BakerUtilities.SetLoopFrame(time, rotW);
BakerUtilities.SetLoopFrame(time, posX);
BakerUtilities.SetLoopFrame(time, posY);
BakerUtilities.SetLoopFrame(time, posZ);
}
private void MoveLastKeyframe(float time, AnimationCurve curve)
{
Keyframe[] keys = curve.keys;
keys[keys.Length - 1].time = time;
curve.keys = keys;
}
public void MultiplyLength(AnimationCurve curve, float mlp)
{
Keyframe[] keys = curve.keys;
for (int i = 0; i < keys.Length; i++)
{
keys[i].time *= mlp;
}
curve.keys = keys;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip, float maxError, float lengthMlp)
{
MultiplyLength(rotX, lengthMlp);
MultiplyLength(rotY, lengthMlp);
MultiplyLength(rotZ, lengthMlp);
MultiplyLength(rotW, lengthMlp);
MultiplyLength(posX, lengthMlp);
MultiplyLength(posY, lengthMlp);
MultiplyLength(posZ, lengthMlp);
BakerUtilities.ReduceKeyframes(rotX, maxError);
BakerUtilities.ReduceKeyframes(rotY, maxError);
BakerUtilities.ReduceKeyframes(rotZ, maxError);
BakerUtilities.ReduceKeyframes(rotW, maxError);
BakerUtilities.ReduceKeyframes(posX, maxError);
BakerUtilities.ReduceKeyframes(posY, maxError);
BakerUtilities.ReduceKeyframes(posZ, maxError);
BakerUtilities.SetTangentMode(rotX);
BakerUtilities.SetTangentMode(rotY);
BakerUtilities.SetTangentMode(rotZ);
BakerUtilities.SetTangentMode(rotW);
/*
BakerUtilities.SetTangentMode(posX);
BakerUtilities.SetTangentMode(posY);
BakerUtilities.SetTangentMode(posZ);
*/
clip.SetCurve(string.Empty, typeof(Animator), Qx, rotX);
clip.SetCurve(string.Empty, typeof(Animator), Qy, rotY);
clip.SetCurve(string.Empty, typeof(Animator), Qz, rotZ);
clip.SetCurve(string.Empty, typeof(Animator), Qw, rotW);
clip.SetCurve(string.Empty, typeof(Animator), Tx, posX);
clip.SetCurve(string.Empty, typeof(Animator), Ty, posY);
clip.SetCurve(string.Empty, typeof(Animator), Tz, posZ);
}
}
// Manages the Animation Curves for a single Transform that is a child of the root Transform.
[System.Serializable]
public class BakerMuscle
{
// Animation curves for each channel of the Transform
public AnimationCurve curve;
private int muscleIndex = -1;
private string propertyName;
// The custom constructor
public BakerMuscle(int muscleIndex)
{
this.muscleIndex = muscleIndex;
this.propertyName = MuscleNameToPropertyName(HumanTrait.MuscleName[muscleIndex]);
Reset();
}
private string MuscleNameToPropertyName(string n)
{
// Left fingers
if (n == "Left Index 1 Stretched") return "LeftHand.Index.1 Stretched";
if (n == "Left Index 2 Stretched") return "LeftHand.Index.2 Stretched";
if (n == "Left Index 3 Stretched") return "LeftHand.Index.3 Stretched";
if (n == "Left Middle 1 Stretched") return "LeftHand.Middle.1 Stretched";
if (n == "Left Middle 2 Stretched") return "LeftHand.Middle.2 Stretched";
if (n == "Left Middle 3 Stretched") return "LeftHand.Middle.3 Stretched";
if (n == "Left Ring 1 Stretched") return "LeftHand.Ring.1 Stretched";
if (n == "Left Ring 2 Stretched") return "LeftHand.Ring.2 Stretched";
if (n == "Left Ring 3 Stretched") return "LeftHand.Ring.3 Stretched";
if (n == "Left Little 1 Stretched") return "LeftHand.Little.1 Stretched";
if (n == "Left Little 2 Stretched") return "LeftHand.Little.2 Stretched";
if (n == "Left Little 3 Stretched") return "LeftHand.Little.3 Stretched";
if (n == "Left Thumb 1 Stretched") return "LeftHand.Thumb.1 Stretched";
if (n == "Left Thumb 2 Stretched") return "LeftHand.Thumb.2 Stretched";
if (n == "Left Thumb 3 Stretched") return "LeftHand.Thumb.3 Stretched";
if (n == "Left Index Spread") return "LeftHand.Index.Spread";
if (n == "Left Middle Spread") return "LeftHand.Middle.Spread";
if (n == "Left Ring Spread") return "LeftHand.Ring.Spread";
if (n == "Left Little Spread") return "LeftHand.Little.Spread";
if (n == "Left Thumb Spread") return "LeftHand.Thumb.Spread";
// Right fingers
if (n == "Right Index 1 Stretched") return "RightHand.Index.1 Stretched";
if (n == "Right Index 2 Stretched") return "RightHand.Index.2 Stretched";
if (n == "Right Index 3 Stretched") return "RightHand.Index.3 Stretched";
if (n == "Right Middle 1 Stretched") return "RightHand.Middle.1 Stretched";
if (n == "Right Middle 2 Stretched") return "RightHand.Middle.2 Stretched";
if (n == "Right Middle 3 Stretched") return "RightHand.Middle.3 Stretched";
if (n == "Right Ring 1 Stretched") return "RightHand.Ring.1 Stretched";
if (n == "Right Ring 2 Stretched") return "RightHand.Ring.2 Stretched";
if (n == "Right Ring 3 Stretched") return "RightHand.Ring.3 Stretched";
if (n == "Right Little 1 Stretched") return "RightHand.Little.1 Stretched";
if (n == "Right Little 2 Stretched") return "RightHand.Little.2 Stretched";
if (n == "Right Little 3 Stretched") return "RightHand.Little.3 Stretched";
if (n == "Right Thumb 1 Stretched") return "RightHand.Thumb.1 Stretched";
if (n == "Right Thumb 2 Stretched") return "RightHand.Thumb.2 Stretched";
if (n == "Right Thumb 3 Stretched") return "RightHand.Thumb.3 Stretched";
if (n == "Right Index Spread") return "RightHand.Index.Spread";
if (n == "Right Middle Spread") return "RightHand.Middle.Spread";
if (n == "Right Ring Spread") return "RightHand.Ring.Spread";
if (n == "Right Little Spread") return "RightHand.Little.Spread";
if (n == "Right Thumb Spread") return "RightHand.Thumb.Spread";
return n;
}
public void MultiplyLength(AnimationCurve curve, float mlp)
{
Keyframe[] keys = curve.keys;
for (int i = 0; i < keys.Length; i++)
{
keys[i].time *= mlp;
}
curve.keys = keys;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip, float maxError, float lengthMlp)
{
MultiplyLength(curve, lengthMlp);
BakerUtilities.ReduceKeyframes(curve, maxError);
// BakerUtilities.SetTangentMode(curve);
clip.SetCurve(string.Empty, typeof(Animator), propertyName, curve);
}
// Clear all curves
public void Reset()
{
curve = new AnimationCurve();
}
// Record a keyframe for each channel
public void SetKeyframe(float time, float[] muscles)
{
curve.AddKey(time, muscles[muscleIndex]);
}
// Add a copy of the first frame to the specified time
public void SetLoopFrame(float time)
{
BakerUtilities.SetLoopFrame(time, curve);
}
}
//Manages the Animation Curves for a single Transform that is a child of the root Transform.
[System.Serializable]
public class BakerTransform
{
public Transform transform; // The Transform component to record
// Animation curves for each channel of the Transform
public AnimationCurve
posX, posY, posZ,
rotX, rotY, rotZ, rotW;
private string relativePath; // Path relative to the root
private bool recordPosition; // Should we record the localPosition if the transform?
private Vector3 relativePosition;
private bool isRootNode;
private Quaternion relativeRotation;
// The custom constructor
public BakerTransform(Transform transform, Transform root, bool recordPosition, bool isRootNode)
{
this.transform = transform;
this.recordPosition = recordPosition || isRootNode;
this.isRootNode = isRootNode;
relativePath = string.Empty;
#if UNITY_EDITOR
relativePath = UnityEditor.AnimationUtility.CalculateTransformPath(transform, root);
#endif
Reset();
}
public void SetRelativeSpace(Vector3 position, Quaternion rotation)
{
relativePosition = position;
relativeRotation = rotation;
}
// Add curves to the AnimationClip for each channel
public void SetCurves(ref AnimationClip clip)
{
if (recordPosition)
{
clip.SetCurve(relativePath, typeof(Transform), "localPosition.x", posX);
clip.SetCurve(relativePath, typeof(Transform), "localPosition.y", posY);
clip.SetCurve(relativePath, typeof(Transform), "localPosition.z", posZ);
}
clip.SetCurve(relativePath, typeof(Transform), "localRotation.x", rotX);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.y", rotY);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.z", rotZ);
clip.SetCurve(relativePath, typeof(Transform), "localRotation.w", rotW);
if (isRootNode) AddRootMotionCurves(ref clip);
// @todo probably only need to do it once for the clip
clip.EnsureQuaternionContinuity(); // DOH!
}
private void AddRootMotionCurves(ref AnimationClip clip)
{
if (recordPosition)
{
clip.SetCurve("", typeof(Animator), "MotionT.x", posX);
clip.SetCurve("", typeof(Animator), "MotionT.y", posY);
clip.SetCurve("", typeof(Animator), "MotionT.z", posZ);
}
clip.SetCurve("", typeof(Animator), "MotionQ.x", rotX);
clip.SetCurve("", typeof(Animator), "MotionQ.y", rotY);
clip.SetCurve("", typeof(Animator), "MotionQ.z", rotZ);
clip.SetCurve("", typeof(Animator), "MotionQ.w", rotW);
}
// Clear all curves
public void Reset()
{
posX = new AnimationCurve();
posY = new AnimationCurve();
posZ = new AnimationCurve();
rotX = new AnimationCurve();
rotY = new AnimationCurve();
rotZ = new AnimationCurve();
rotW = new AnimationCurve();
}
public void ReduceKeyframes(float maxError)
{
BakerUtilities.ReduceKeyframes(rotX, maxError);
BakerUtilities.ReduceKeyframes(rotY, maxError);
BakerUtilities.ReduceKeyframes(rotZ, maxError);
BakerUtilities.ReduceKeyframes(rotW, maxError);
BakerUtilities.ReduceKeyframes(posX, maxError);
BakerUtilities.ReduceKeyframes(posY, maxError);
BakerUtilities.ReduceKeyframes(posZ, maxError);
}
// Record a keyframe for each channel
public void SetKeyframes(float time)
{
if (recordPosition)
{
Vector3 pos = transform.localPosition;
if (isRootNode)
{
pos = transform.position - relativePosition;
}
posX.AddKey(time, pos.x);
posY.AddKey(time, pos.y);
posZ.AddKey(time, pos.z);
}
Quaternion rot = transform.localRotation;
if (isRootNode)
{
rot = Quaternion.Inverse(relativeRotation) * transform.rotation;
}
rotX.AddKey(time, rot.x);
rotY.AddKey(time, rot.y);
rotZ.AddKey(time, rot.z);
rotW.AddKey(time, rot.w);
}
// Add a copy of the first frame to the specified time
public void AddLoopFrame(float time)
{
// TODO change to SetLoopFrame
if (recordPosition && !isRootNode)
{
posX.AddKey(time, posX.keys[0].value);
posY.AddKey(time, posY.keys[0].value);
posZ.AddKey(time, posZ.keys[0].value);
}
rotX.AddKey(time, rotX.keys[0].value);
rotY.AddKey(time, rotY.keys[0].value);
rotZ.AddKey(time, rotZ.keys[0].value);
rotW.AddKey(time, rotW.keys[0].value);
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 582052db0a6096149a7b2b75914ef3a6
timeCreated: 1516263395
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,194 +0,0 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Playables;
namespace RootMotion
{
/// <summary>
/// Baker for Humanoid animation.
/// </summary>
public class HumanoidBaker : Baker
{
/// <summary>
/// Should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.
/// </summary>
[Tooltip("Should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.")]
public bool bakeHandIK = true;
/// <summary>
/// Max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
/// </summary>
[Tooltip("Max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.")]
[Range(0f, 0.1f)] public float IKKeyReductionError;
/// <summary>
/// Frame rate divider for the muscle curves. If you had 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
/// </summary>
[Tooltip("Frame rate divider for the muscle curves. If you have 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.")]
[Range(1, 9)] public int muscleFrameRateDiv = 1;
private BakerMuscle[] bakerMuscles;
private BakerHumanoidQT rootQT;
private BakerHumanoidQT leftFootQT;
private BakerHumanoidQT rightFootQT;
private BakerHumanoidQT leftHandQT;
private BakerHumanoidQT rightHandQT;
private float[] muscles = new float[0];
private HumanPose pose = new HumanPose();
private HumanPoseHandler handler;
private Vector3 bodyPosition;
private Quaternion bodyRotation = Quaternion.identity;
private int mN = 0;
private Quaternion lastBodyRotation = Quaternion.identity;
void Awake()
{
animator = GetComponent<Animator>();
director = GetComponent<PlayableDirector>();
if (mode == Mode.AnimationStates || mode == Mode.AnimationClips)
{
if (animator == null || !animator.isHuman)
{
Debug.LogError("HumanoidBaker GameObject does not have a Humanoid Animator component, can not bake.");
enabled = false;
return;
}
animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
}
else if (mode == Mode.PlayableDirector)
{
if (director == null)
{
Debug.LogError("HumanoidBaker GameObject does not have a PlayableDirector component, can not bake.");
}
}
muscles = new float[HumanTrait.MuscleCount];
bakerMuscles = new BakerMuscle[HumanTrait.MuscleCount];
for (int i = 0; i < bakerMuscles.Length; i++)
{
bakerMuscles[i] = new BakerMuscle(i);
}
rootQT = new BakerHumanoidQT("Root");
leftFootQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.LeftFoot), AvatarIKGoal.LeftFoot, "LeftFoot");
rightFootQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.RightFoot), AvatarIKGoal.RightFoot, "RightFoot");
leftHandQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.LeftHand), AvatarIKGoal.LeftHand, "LeftHand");
rightHandQT = new BakerHumanoidQT(animator.GetBoneTransform(HumanBodyBones.RightHand), AvatarIKGoal.RightHand, "RightHand");
handler = new HumanPoseHandler(animator.avatar, animator.transform);
}
protected override Transform GetCharacterRoot()
{
return animator.transform;
}
protected override void OnStartBaking()
{
rootQT.Reset();
leftFootQT.Reset();
rightFootQT.Reset();
leftHandQT.Reset();
rightHandQT.Reset();
for (int i = 0; i < bakerMuscles.Length; i++)
{
bakerMuscles[i].Reset();
}
mN = muscleFrameRateDiv;
lastBodyRotation = Quaternion.identity;
}
protected override void OnSetLoopFrame(float time)
{
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetLoopFrame(time);
rootQT.MoveLastKeyframes(time);
leftFootQT.SetLoopFrame(time);
rightFootQT.SetLoopFrame(time);
leftHandQT.SetLoopFrame(time);
rightHandQT.SetLoopFrame(time);
}
protected override void OnSetCurves(ref AnimationClip clip)
{
float length = bakerMuscles[0].curve.keys[bakerMuscles[0].curve.keys.Length - 1].time;
float lengthMlp = mode != Mode.Realtime ? clipLength / length : 1f;
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetCurves(ref clip, keyReductionError, lengthMlp);
rootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
leftFootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
rightFootQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
if (bakeHandIK)
{
leftHandQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
rightHandQT.SetCurves(ref clip, IKKeyReductionError, lengthMlp);
}
}
protected override void OnSetKeyframes(float time, bool lastFrame)
{
// Skip muscle frames
mN++;
bool updateMuscles = true;
if (mN < muscleFrameRateDiv && !lastFrame)
{
updateMuscles = false;
}
if (mN >= muscleFrameRateDiv) mN = 0;
UpdateHumanPose();
if (updateMuscles)
{
for (int i = 0; i < bakerMuscles.Length; i++) bakerMuscles[i].SetKeyframe(time, muscles);
}
rootQT.SetKeyframes(time, bodyPosition, bodyRotation);
Vector3 bodyPositionScaled = bodyPosition * animator.humanScale;
leftFootQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
rightFootQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
leftHandQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
rightHandQT.SetIKKeyframes(time, animator.avatar, animator.humanScale, bodyPositionScaled, bodyRotation);
}
private void UpdateHumanPose()
{
handler.GetHumanPose(ref pose);
bodyPosition = pose.bodyPosition;
bodyRotation = pose.bodyRotation;
bodyRotation = BakerUtilities.EnsureQuaternionContinuity(lastBodyRotation, bodyRotation);
lastBodyRotation = bodyRotation;
for (int i = 0; i < pose.muscles.Length; i++)
{
muscles[i] = pose.muscles[i];
}
}
#if UNITY_EDITOR
protected override void SetClipSettings(AnimationClip clip, UnityEditor.AnimationClipSettings settings)
{
settings.loopBlendOrientation = true;
settings.loopBlendPositionY = true;
settings.keepOriginalOrientation = true;
settings.keepOriginalPositionY = true;
}
#endif
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: efcc0ec5ed265a340a1412edb9110337
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 10150
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: c41cf13236c01a747b3dfb963402b3a0
folderAsset: yes
timeCreated: 1516620909
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: a4b02f60233a6cf4eb1c424f90323213
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 3451f091c656bfc429396cc701ac5b8d
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 7400000
userData:
assetBundleName:
assetBundleVariant:
@@ -1,69 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!91 &9100000
AnimatorController:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Humanoid Baker Clip Sampler
serializedVersion: 5
m_AnimatorParameters: []
m_AnimatorLayers:
- serializedVersion: 5
m_Name: Base Layer
m_StateMachine: {fileID: 110737558}
m_Mask: {fileID: 0}
m_Motions: []
m_Behaviours: []
m_BlendingMode: 0
m_SyncedLayerIndex: -1
m_DefaultWeight: 0
m_IKPass: 0
m_SyncedLayerAffectsTiming: 0
m_Controller: {fileID: 9100000}
--- !u!1102 &110235224
AnimatorState:
serializedVersion: 5
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Clip 1
m_Speed: 1
m_CycleOffset: 0
m_Transitions: []
m_StateMachineBehaviours: []
m_Position: {x: 50, y: 50, z: 0}
m_IKOnFeet: 1
m_WriteDefaultValues: 1
m_Mirror: 0
m_SpeedParameterActive: 0
m_MirrorParameterActive: 0
m_CycleOffsetParameterActive: 0
m_TimeParameterActive: 0
m_Motion: {fileID: 7400000, guid: 739b2627204c24240aa40c4f67f59d0e, type: 3}
m_Tag:
m_SpeedParameter:
m_MirrorParameter:
m_CycleOffsetParameter:
m_TimeParameter:
--- !u!1107 &110737558
AnimatorStateMachine:
serializedVersion: 5
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Base Layer
m_ChildStates:
- serializedVersion: 1
m_State: {fileID: 110235224}
m_Position: {x: 300, y: 36, z: 0}
m_ChildStateMachines: []
m_AnyStateTransitions: []
m_EntryTransitions: []
m_StateMachineTransitions: {}
m_StateMachineBehaviours: []
m_AnyStatePosition: {x: 50, y: 20, z: 0}
m_EntryPosition: {x: 50, y: 120, z: 0}
m_ExitPosition: {x: 800, y: 120, z: 0}
m_ParentStateMachinePosition: {x: 800, y: 20, z: 0}
m_DefaultState: {fileID: 110235224}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 24d41cb619dc9dc42bf10705eb128c97
timeCreated: 1516284817
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 0bd8d9a8cbacde343967c95c4458318e
timeCreated: 1517387718
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 3349a7526568cf042bf8609694db3327
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,53 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace RootMotion.Demos
{
// Adds simple FK rotation offset to bones.
public class FKOffset : MonoBehaviour
{
[System.Serializable]
public class Offset
{
[HideInInspector][SerializeField] public string name;
public HumanBodyBones bone;
public Vector3 rotationOffset;
private Transform t;
public void Apply(Animator animator)
{
if (t == null) t = animator.GetBoneTransform(bone);
if (t == null) return;
t.localRotation *= Quaternion.Euler(rotationOffset);
}
}
public Offset[] offsets;
private Animator animator;
private void Start()
{
animator = GetComponent<Animator>();
}
private void LateUpdate()
{
foreach (Offset offset in offsets)
{
offset.Apply(animator);
}
}
private void OnDrawGizmosSelected()
{
foreach (Offset offset in offsets)
{
offset.name = offset.bone.ToString();
}
}
}
}
@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ea198996b9a58624b82f921e56faf4ba
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 96b187132b9a544c8a08d5b29323cc10
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,762 +0,0 @@
/*! \mainpage
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/on7wAz0fsGg" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<br>Welcome to PuppetMaster, an advanced character physics tool for Unity!
\section contains PuppetMaster Contains
- Tools for animating ragdolls of any kind
- Automated, easy to use ragdoll generator for all biped characters
- Ragdoll Editor - enabling you to intuitively edit colliders and joints in the Scene View.
- Joint Inspectors - visualizing and editing Character and Configurable Joints in the Scene View
\section technicaloverview Technical Overview
- Does NOT require Unity Pro
- Works with Humanoid, Generic and Legacy characters.
- Written in C#, all scripts are namespaced under %RootMotion and %RootMotion.Dynamics to avoid any naming conflicts with Your existing assets.
- Tested on Standalone, Web Player, IOS and Android
- Custom undoable inspectors and scene view handles
- Warning system to safeguard from null references and invalid setups (will not overflow your console with warnings)
- Optimized for great performance
- Modular, easily extendable. Compose your own custom character rigs
- User manual, HTML documentation, fully documented code
- Demo scenes and example scripts for all components
- Tested on a wide range of characters
*/
/*! \page page1 Creating Ragdolls
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/y-luLRVmL7E?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>BipedRagdollCreator</b>
<br>
PuppetMaster contains a very easy to use visual ragdoll creation tool for biped characters (can actually be used on any character with at least 4 limbs) called BipedRagdollCreator.
When the BipedRagdollCreator.cs component is enabled on a character, the ragdoll components will be destroyed and recreated each time you change the references or options.
This enables for fast and intuitive live editing.
<b>Getting started</b>
- Drag a character model to the scene and attach the BipedRagdollCreator.cs component. Biped bone references will be filled in automatically if it is a Humanoid character. In other cases, they can be filled in manually.
- Click on "Create a Ragdoll" to start live-updating and editing the ragdoll. You should then see the Rigidbody, Collider and Joint components added to the character.
- Note that with all adjustments to the parameters of BipedRagdollCreator the ragdoll components will be deleted and recreated, so do not make any references to them until the BipedRagdollCreator has been removed.
- Only ConfigurableJoints are supported by the PuppetMaster at this time so use "Configurable" as "Joints".
- Once you are happy with the basic Collider and Joint types and other settings in the "Options", click on "Start Editing Manually" to make final manual adjustments using the RagdollEditor. This will remove the BipedRagdollCreator component.
<b>Component variables:</b>
- <b>references</b> - references to the biped bones.
- <b>weight</b> - the total weight of the character. Will be distributed biometrically between the ragdoll Rigidbodies.
- <b>spine</b> - toggle the spine bone included in the ragdoll.
- <b>chest</b> - toggle the chest bone included in the ragdoll.
- <b>hands</b> - toggle the hand bones included in the ragdoll.
- <b>feet</b> - toggle the foot bones included in the ragdoll.
- <b>joints</b> - build the ragdoll with ConfigurableJoints or CharacterJoints? NB! PuppetMaster can use only ConfigurableJoints.
- <b>jointRange</b> - multiplies joint limit ranges.
- <b>colliderLengthOverlap</b> - determines how much the colliders overlap each other, supports also negative values.
- <b>torsoColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>headCollider</b> - use BoxCollider or CapsuleCollider for the body part.
- <b>armColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>handColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>legColliders</b> - use BoxColliders or CapsuleColliders for the body part.
- <b>footColliders</b> - use BoxColliders or CapsuleColliders for the body part.
\image html BipedRagdollCreator2.png
<b>Creating ragdolls in runtime:</b>
\code
[Tooltip("The character prefab/FBX.")]
public GameObject prefab;
void Start() {
// Instantiate the character
GameObject instance = GameObject.Instantiate(prefab);
// Find bones (Humanoids)
BipedRagdollReferences r = BipedRagdollReferences.FromAvatar(instance.GetComponent<Animator>());
// How would you like your ragdoll?
BipedRagdollCreator.Options options = BipedRagdollCreator.AutodetectOptions(r);
// Edit options here if you need to
//options.headCollider = RagdollCreator.ColliderType.Box;
//options.weight *= 2f;
//options.joints = RagdollCreator.JointType.Character;
// Create the ragdoll
BipedRagdollCreator.Create(r, options);
Debug.Log("A ragdoll was successfully created.");
}
void Update() {
// If bone proportions have changed, just clear and recreate:
//BipedRagdollCreator.ClearBipedRagdoll(r); //ClearAll if you have changed references
//BipedRagdollCreator.Create(r, options);
}
\endcode
*/
/*! \page page2 Editing Ragdolls
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/y-luLRVmL7E?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>RagdollEditor</b>
<br>
RagdollEditor is an intuitive visualized and Scene View tool for editing Colliders, Joints and Rigidbody settings. Symmetry is supported for collider position, size and joint limit editing. All actions with the RagdollEditor are undoable.
\image html RagdollEditorScene.png
<b>Getting started</b>
- Add the RagdollEditor.cs component to the root of the ragdoll.
- Click on the green buttons on the Colliders/Joints to select them.
- Use the Move/Scale handles to edit the Colliders and Joints in the Scene View.
- Remove the component when you are done.
<b>Component interface:</b>
- <b>Mass Multiplier</b> - multiplies the mass of all the Rigidbodies with the value.
- <b>Set All Kinematic</b> - set all Rigidbodies kinematic.
- <b>Set All Non-Kinematic</b> - set all Rigidbodies non-kinematic.
- <b>Disable Preprocessing</b> - uncheck 'enablePreprocessing' on all Joints. This can make the ragdoll more stable under certain circumstances.
- <b>Enable Preprocessing</b> - check 'enablePreprocessing' on all Joints.
\image html RagdollEditor.png
<b>Collider tool:</b>
- <b>Select GameObject</b> - changes Unity selection to the currently edited Collider's GameObject
- <b>Edit Mode</b> - switch to Joint editing mode.
- <b>Symmetry</b> - enables symmetric editing. Symmetry works for the closest Collider (within a threshold) on the other side of the ZY plane (local space of the GameObject of RagdollEditor).
- <b>Convert To Capsule Collider</b> - converts the selected collider to CapsuleCollider.
- <b>Convert To Sphere Collider</b> - converts the selected collider to SphereCollider.
- <b>Rotate Collider</b> - rotates the collider size vector orthogonally.
\image html RagdollEditorColliders.png
<b>Joint tool:</b>
- <b>Select GameObject</b> - changes Unity selection to the currently edited Joint's GameObject
- <b>Edit Mode</b> - switch to Collider editing mode.
- <b>Symmetry</b> - enables symmetric editing. Symmetry works for the closest Joint (within a threshold) on the other side of the ZY plane (local space of the GameObject of RagdollEditor).
- <b>Connected Body</b> - select or change the connectedBody of the selected Joint.
- <b>Switch Yellow/Green</b> - switches the respective Joint axes.
- <b>Switch Yellow/Blue</b> - switches the respective Joint axes.
- <b>Switch Green/blue</b> - switches the respective Joint axes.
- <b>Invert Yellow</b> - inverts Joint.axis.
\image html RagdollEditorJoints.png
*/
/*! \page page3 PuppetMaster Overview
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/on7wAz0fsGg" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<br>
<b>Terminology</b>
<br>
PuppetMaster uses a <b>"Dual Rig"</b> that consists of the normal animated character (from hereby: <b>"Target"</b>) and the simplified ragdoll structure (<b>"Puppet"</b>).
The main purpose of PuppetMaster is to make the Puppet ragdoll physically follow the motion and animation of the animated Target character.
It will do so by two means, first is articulating the joints (<b>"Muscles"</b>), the other is pinning the rigidbodies to their targets using AddForce commands (<b>"Pins"</b>).
The classes that control the behaviour of the Muscles and handle their strength, pinning and other properties are called <b>"Puppet Behaviours"</b>.
The dual rig and the Behaviours will share a common parent GameObject (<b>"Root"</b>) that serves as a container for the PuppetMaster character rig.
The kinematic Target character will be mapped to the dynamic Puppet ragdoll by the means of <b>"Mapping"</b>, which can also be smoothly blended in and out for the entire character or for each Muscle separately.
<b>Dual Rig</b>
<br>
\image html DualRigExplained.png
The main advantage of using a dual rig over a single character setup is performance. It is much less expensive mostly due to not having the necessity of performing costly transformations with objects that have Colliders attached.
The performance win becomes even greater when having to do IK/FK procedures on the target pose. The PuppetMaster can be smoothly blended to run in Kinematic or Disabled mode. The former will simply make the ragdoll kinematic and match it with the target, the latter will completely deactivate the ragdoll when you don't need it.
The dual rig also allows for choosing between flat or tree hierarchy modes for the ragdoll (click "Flat/Tree Hierarhcy" from the PuppetMaster's context menu) and will allow for sharing ragdolls between multiple characters in a future release of PuppetMaster.
The PuppetMaster will automatically set up the dual rig for you when provided with a reference to a traditional ragdoll character.
<b>Target</b>
<br>
\image html Target.png
The Target can be thought of as the normal animated character that you would see in any game, it usually has a character controller and any other gameplay components attached.
Each frame, PuppetMaster will read the pose of the Target and feed it to the Muscles of the Puppet for following.
After physics has solved, the Target will be mapped to the pose of the Puppet based on the mapping settings and stay there until animation overwrites it the next frame.
<b>Puppet</b>
<br>
\image html Puppet.png
The simplified ragdoll structure (Puppet) is essentially a duplicate of the Target, but with ragdoll Components attached and all other Components and GameObjects unrelated to physics stripped.
The PuppetMaster requires for the ragdoll to be set up using ConfigurableJoints only. Any other Joint can be converted to a ConfigurableJoint by selecting the (root) GameObject and clicking on "GameObject/Convert to ConfigurableJoints" from the menu bar.
The Puppet ragdoll can be set up in tree or flat hierarchy modes (click "Flat/Tree Hierarhcy" from the PuppetMaster's context menu).
<b>Muscles</b>
<br>
\image html Muscles.png
The PuppetMaster will turn each ConfigurableJoint of the Puppet into a Muscle that maintains a reference to it's animated target and automatically calculates Joint target rotations, pinning forces and other values.
When the Puppet is unpinned, the ragdoll will follow the animation in muscle space and the result is physically authentic and accurate.
When pinned, the pinning forces will move the ragdoll bones to the world space position of their targets, they can be imagined as spring joints pulling each ragdoll bone towards their animated target.
Pinning is therefore an unnatural force that can be managed to make the ragdoll simulate game character motion that physically would be almost unachievable.
The Muscles are listed in the PuppetMaster's inspector, each having individual properties, enabling you to specify the physical behaviour of each Muscle or Muscle Group.
<b>Modes</b>
<br>
\image html Modes.png
The PuppetMaster can run in 3 Modes. <b>Active</b> is the active ragdoll mode that makes the Puppet physically follow it's Target by employing the muscle forces, pins or both at the same time. The Puppet is able to collide with and be affected by objects in the scene.
The <b>Kinematic</b> mode makes the Rigidbodies of the Puppet kinematic and the Muscles will not be used anymore. The Puppet is still able to collide with objects and receive raycast hits.
The <b>Disabled</b> mode completely deactivates the Puppet along with it's Rigidbodies and Colliders. In Disabled mode the PuppetMaster will not have any effect on the performance. All modes can be blended in/out smoothly in respect to the "Blend Time" parameter.
<b>Puppet Behaviours</b>
<br>
\image html Behaviours2.png
The Puppet Behaviours are classes that inherit from the abstract BehaviourBase.cs and that's main idea is to provide a pattern for developing functionalities that dynamically adjust muscle and pin weights, strength and other properties or make kinematic adjustments to the target pose.
The most important Puppet Behaviour is the BehaviourPuppet.cs that handles the pinning of Puppets to target animation, releasing those pins in case of collision and re-tightening them when getting up from the ground.
The Puppet Behaviours can be switched, for example when the BehaviourPuppet looses balance, it can theoretically switch to BehaviourCatchFall or BehaviourWindmill (both missing from the initial release, but will be developed in the future).
The Puppet Behaviours are designed so tha they would not contain a single external object reference. That means they can be simply duplicated and moved to another Puppet.
*/
/*! \page page4 PuppetMaster Setup
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/mIN9bxJgfOU?list=PLVxSIA1OaTOuE2SB9NUbckQ9r2hTg4mvL" frameborder="0" allowfullscreen></iframe>\endhtmlonly
To set up a character with ragdoll components as a Puppet, the easiest way is to simply add the PuppetMaster component to it and click on the "Set Up PuppetMaster" button.
That will make a duplicate of the character and set the duplicate up as the Puppet while the selected instance will become the Target. Both will be parented to a new GameObject that is the root container for the entire character rig.
A GameObject with the character's name + " Behaviours" will also be added. All Puppet Behaviours (BehaviourPuppet, BehaviourFall...) should be parented to it.
Alternately you can assign another character hierarchy to become the Target. PuppetMaster supports sharing ragdolls between multiple characters as long as the positions of the muscles match with their targets.
Rotations can be different, so you can even use another rig with different bone orientations.
"Character Controller Layer" and "Ragdoll Layer" will be applied to the Target and Puppet respectively to avoid collisions between the character controller and the ragdoll colliders.
Make sure collisions between the two layers are disabled in the Edit/Project Settings/Physics/Layer Collision Matrix.
\image html PuppetMasterSetup.png
<b>Creating puppets in run-time</b>
<br>
The procedure and code for setting up puppets in run-time is demonstrated in the "Creating Puppets In Runtime" demo scene and CreatePuppetInRuntime.cs script.
It requires for the character to be already set up with ragdoll components.
\code
Transform ragdoll = GameObject.Instantiate(ragdollPrefab, transform.position, transform.rotation) as Transform;
ragdoll.name = instanceName;
// This will duplicate the "ragdoll" instance, remove the ragdoll components from the original and use it as the animated target, setting the duplicate up as a puppet.
PuppetMaster.SetUp(ragdoll, characterControllerLayer, ragdollLayer);
// or...
//PuppetMaster.SetUp(target, ragdoll, characterControllerLayer, ragdollLayer);
// or if you want the "ragdoll" instance to become the puppet, not the target:
//PuppetMaster.SetUpTo(target, characterControllerLayer, ragdollLayer);
Debug.Log("A ragdoll was successfully converted to a Puppet.");
\endcode
*/
/*! \page page5 PuppetMaster Component
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/LYusqeqHAUc" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Simulation</b>
- <b>state</b> - sets/sets the state of the puppet (Alive, Dead or Frozen). Frozen means the ragdoll will be deactivated once it comes to stop in dead state.
- <b>stateSettings</b> - settings for killing and freezing the puppet.
<BR><b>killDuration</b> - how much does it take to weigh out muscle weight to deadMuscleWeight?
<BR><b>deadMuscleWeight</b> - the muscle weight mlp while the puppet is Dead.
<BR><b>deadMuscleDamper</b> - the muscle damper add while the puppet is Dead.
<BR><b>maxFreezeSqrVelocity</b> - the max square velocity of the ragdoll bones for freezing the puppet.
<BR><b>freezePermanently</b> - if true, PuppetMaster, all it's behaviours and the ragdoll will be destroyed when the puppet is frozen.
<BR><b>enableAngularLimitsOnKill</b> - if true, will enable angular limits when killing the puppet.
<BR><b>enableInternalCollisionsOnKill</b> - if true, will enable internal collisions when killing the puppet.
- <b>mode</b> - Active mode means all muscles are active and the character is physically simulated. Kinematic mode sets rigidbody.isKinematic to true for all the muscles and simply updates their position/rotation to match the target's. Disabled mode disables the ragdoll. Switching modes is done by simply changing this value, blending in/out will be handled automatically by the PuppetMaster.
- <b>blendTime</b> - the time of blending when switching from Active to Kinematic/Disabled or from Kinematic/Disabled to Active. Switching from Kinematic to Disabled or vice versa will be done instantly.
- <b>fixTargetTransforms</b> - if true, will fix the target character's Transforms to their default local positions and rotations in each update cycle to avoid drifting from additive reading-writing. Use this only if the target contains unanimated bones.
- <b>solverIterationCount</b> - Rigidbody.solverIterationCount for the muscles of this Puppet.
- <b>visualizeTargetPose</b> - if true, will draw the target's pose as green lines in the Scene view. This runs in the Editor only. If you wish to profile PuppetMaster, switch this off.
<b>Master Weights</b>
- <b>mappingWeight</b> - the weight of mapping the animated character to the ragdoll pose.
- <b>pinWeight</b> - the weight of pinning the muscles to the position of their animated targets using simple AddForce.
- <b>muscleWeight</b> - the normalized strength of the muscles.
<b>Joint and Muscle Settings</b>
- <b>muscleSpring</b> - the positionSpring of the ConfigurableJoints' Slerp Drive.
- <b>muscleDamper</b> - the positionDamper of the ConfigurableJoints' Slerp Drive.
- <b>pinPow</b> - adjusts the slope of the pinWeight curve. Has effect only while interpolating pinWeight from 0 to 1 and back.
- <b>pinDistanceFalloff</b> - reduces pinning force the farther away the target is. Bigger value loosens the pinning, resulting in sloppier behaviour.
- <b>updateJointAnchors</b> - when the target has animated bones between the muscle bones, the joint anchors need to be updated in every update cycle because the muscles' targets move relative to each other in position space. This gives much more accurate results, but is computationally expensive so consider leaving it off.
- <b>supportTranslationAnimation</b> - enable this if any of the target's bones has translation animation.
- <b>angularLimits</b> - should the joints use angular limits? If the PuppetMaster fails to match the target's pose, it might be because the joint limits are too stiff and do not allow for such motion. Uncheck this to see if the limits are clamping the range of your puppet's animation. Since the joints are actuated, most PuppetMaster simulations will not actually require using joint limits at all.
- <b>internalCollisions</b> - should the muscles collide with each other? Consider leaving this off while the puppet is pinned for performance and better accuracy. Since the joints are actuated, most PuppetMaster simulations will not actually require internal collisions at all.
<b>Individual Muscle Settings:</b>
- <b>joint</b> - the ConfigurableJoint used by this muscle.
- <b>target</b> - the target Transform that this muscle tries to follow.
- <b>props</b> - the main properties of the muscle.
<BR><b>group</b> - which body part does this muscle belong to? This might be used by some behaviours (BehaviourPuppet).
<BR><b>mappingWeight</b> - the weight (multiplier) of mapping this muscle's target to the muscle.
<BR><b>pinWeight</b> - the weight (multiplier) of pinning this muscle to it's target's position using a simple AddForce command.
<BR><b>muscleWeight</b> - the muscle strength (multiplier).
<BR><b>muscleDamper</b> - multiplier of the positionDamper of the ConfigurableJoints' Slerp Drive.
<BR><b>mapPosition</b> - if true, will map the target to the world space position of the muscle. Normally this should be true for only the root muscle (the hips).
\image html PuppetMaster.png
*/
/*! \page page6 Props
PuppetMaster includes a helpful tool for attaching, detatching and managing physical props - the <b>PropMuscle</b> and <b>PuppetMasterProp</b> classes.
PropMuscle is a special type of muscle that the PuppetMasterProp objects can be attached to.
For an example of prop usage, please see the "Prop" and "Melee" demo scenes.
<b>Getting Started:</b>
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/Bkw1gmrDr1I" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Prop Setup:</b>
Because of the dual rig structure, the prop needs to be set up so that it's root GameObject is the Muscle with the Rigidbody and ConfigurableJoint components and parented to it the Target along with it's mesh and renderer(s).
When the prop is picked up, the prop will be split up so that the "Mesh Root" will be parented to the Target root hierarchy and the rest of the prop with colliders to the Prop Muscle. When the prop is dropped, original hierarchy will be restored.
When the prop is picked up, the Rigidbody component on it will be destroyed as the PropMuscle already has a Rigidbody. The colliders of the prop will act as compound colliders for the PropMuscle Rigidbody. When the prop is dropped, the original Rigidbody will be restored.
\image html Prop.png
\image html PropScene.png
<br>
<b>PropMuscle component:</b>
PropMuscle is a special type of muscle, which all prop objects can be attached to. You can create a PropMuscle in the Editor by selecting the PuppetMaster GameObject and clicking on "Add Prop Muscle" on the bottom of the PuppetMaster component.
Click on the blue button in the scene representing the PropMuscle and move/rotate it to where you need it to be.
If your puppet does not have hand muscles and the PropMuscle was attached to the forearm muscle, find the Prop Muscle Target GameObject in the Target Root hierarchy and parent it to the hand bone.
- <b>Remove This Prop Muscle</b> - destroy this PropMuscle object.
- <b>currentProp</b> - the PuppetMasterProp currently held by this Prop Muscle. To pick up a prop, just assign it as propMuscle.currentProp. To drop, set propMuscle.currentProp to null. Replacing this value with another prop drops any previously held props.
- <b>additionalPinOffset</b> - offset of the additional pin from this Prop Muscle in local space.
- <b>Add/Remove Additional Pin</b> - adds or removes the additional pin object. Additional Pins help to pin this prop muscle to animation from another point. Without it, the prop muscle would be actuated by Muscle Spring only, which is likely not enough to follow fast swinging animations. Move the additional pin by 'Additional Pin Offset' towards the end of the prop (tip of the sword).
\image html PropMuscle.png
Picking up, dropping and switching props with the PropMuscle is done by simply changing the propMuscle.currentProp value. When you assign a prop to it by propMuscle.currentProp = myProp, any props held by the PropMuscle will be dropped and the new myProp will be attached instead.
If you set currentProp to null, any props held by the PropMuscle will be dropped and the PropMuscle itself deactivated.
\code
// Dropping props
propMuscle.currentProp = null;
// Dropping any props held, picking up myProp
propMuscle.currentProp = myProp;
\endcode
When a prop is attached to the PropMuscle, it's localPosition and localRotation are set to zero/identity, so the best practice to adjust prop holding pivot would be to parent the prop to the PropMuscle, set localPosition/Rotation to zero and adjust the positions of the mesh and colliders until they fit perfectly at hand.
<br>
<b>PuppetMasterProp component:</b>
- <b>meshRoot</b> - Mesh Root will be parented to Prop Muscle's target when this prop is picked up. To make sure the mesh and the colliders match up, Mesh Root's localPosition/Rotation must be zero.
- <b>muscleProps</b> - the muscle properties that will be applied to the Prop Muscle when this prop is picked up.
- <b>internalCollisionIgnores</b> - defines which muscles or muscle groups internal collisions will always be ignored with regardless of PuppetMaster.internalCollisions state.
- <b>animatedTargetChildren</b> - list of animated bones parented to this muscle's Target, except for the bones that are targets or target children of any child muscles. This is used for stopping animation on those bones when the muscle has been disconnected using PuppetMaster.DisconnectMuscleRecursive(). For example if you disconnected the spine02 muscle, you would want to have spine03 and clavicles in this list to stop them from animating.
- <b>forceLayers</b> - if true, this prop's layer will be forced to PuppetMaster layer and target's layer forced to PuppetMaster's Target Root's layer when the prop is picked up.
- <b>mass</b> - mass of the prop while picked up. When dropped, mass of the original Rigidbody will be used.
- <b>propType</b> - this has no other purpose but helping you distinguish props by PropRoot.currentProp.propType.
- <b>pickedUpMaterial</b> - if assigned, sets prop colliders to this PhysicMaterial when picked up. If no materials assigned here, will maintain the original PhysicMaterial.
- <b>additionalPinOffsetAdd</b> - adds this to Prop Muscle's 'Additional Pin Offset' when this prop is picked up.
- <b>additionalPinWeight</b> - the pin weight of the additional pin. Increasing this weight will make the prop follow animation better, but will increase jitter when colliding with objects.
- <b>additionalPinMass</b> - multiplies the mass of the additional pin by this value when this prop is picked up. The Rigidbody on this prop will be destroyed on pick-up and reattached on drop, so it's mass is not used while picked up.
\image html PuppetMasterProp.png
<br>
<b>Melee Props:</b>
Lengthy melee props are a huge challenge to the PuppetMaster. Swinging them rapidly requires a lot of muscle force and solver iterations to fight the inertia and keep the ragdoll chain intact.
The longer the chain of Joints linked together, the more inaccurate/unstable the simulation and unfortunatelly those melee props tend to be exactly at the ends of very long Joint chains (pelvis/spine/chest/upper arm/forearm/hand/sword).
Besides that, as the props are swinged, they have a lot of linear and angular velocity, a very thin collider and therefore can easily skip the victim when it's collider happens to be at the position between two fixed frames.
It usually takes quite a lot of tweaking and some tricks to get the melee props working right. PropMuscles have the "Additional Pin" functionality which can be used to add another pinning point to the prop, helping to better pin it to high angular velocity animation.
- make the collider thicker when hitting to decrease collider skipping.
- use Continuous/Continuous Dynamic collision detection modes to reduce skipping, this however has a big performance cost.
- reduce the fixed timestep.
- use the "Additional Pin" (Prop.cs).
- adjust the position of the "Additional Pin" and "Additional Pin Target" along the prop.
- reduce PuppetMaster.pinDistanceFalloff.
- increase PuppetMaster.muscleSpring and solverIterationCount.
- disable PuppetMaster.internalCollisions to prevent the big prop collider from colliding with the Puppet.
- get rid of the hand Muscle to make the joint chain shorter.
<b>PropMelee Component:</b> (this component will be made more generic in PuppetMaster 0.4).
- <b>capsuleCollider</b> - switches the collider to a Capsule when the prop is picked up. Capsules collide more smoothly and with less jitter.
- <b>boxCollider</b> - switches back to this BoxCollider when dropped.
- <b>actionColliderRadiusMlp</b> - multiplies the radius of the Capsule when PropMelee.StartAction(float duration) is called.
- <b>actionAdditionalPinWeight</b> - temporarily set (increase) the pin weight of the additional pin when PropMelee.StartAction(float duration) is called.
- <b>actionMassMlp</b> - temporarily increase the mass of the Rigidbody when PropMelee.StartAction(float duration) is called.
- <b>COMOffset</b> - offset to the default center of mass of the Rigidbody (might improve prop handling).
\image html PuppetMasterPropMelee.png
*/
/*! \page page7 Inverse Kinematics
PuppetMaster can be used together with Unity's own built-in Animator IK as well as Final IK.
The former is limited to Humanoids only and can be used to alter the target pose programmatically before the PuppetMaster reads it for following.
Final IK opens up much more possibilities such as modifying the pose with full body IK or applying an IK pass on top of the physical simulation for cosmetic corrections or accurate aiming.
<b>Final IK:</b>
To use PuppetMaster with Final IK, import both packages to the project, then import also "Plugins/RootMotion/PuppetMaster/_Integration/Final-IK.unitypackage".
The package comes with scenes and scripts demonstrating the application of IK both before and after PuppetMaster solves.
<b>IK Before Physics:</b>
We might be interested in using IK to change the Target pose for various reasons, for example keeping balance, aiming, grabbing, protecting from incoming collisions or even procedural locomotion.
When using Unity's built-in IK solution, it will be automatically applied on top of the animation in the Mecanim update cycle.
The components of Final IK will also update by default before PuppetMaster reads.
If you need them to be updated in a specific order, you can use the IKBeforePhysics.cs component
or disable them and update their solvers manually using the PuppetMaster.OnRead delegate:
\code
public PuppetMaster puppetMaster;
public IK[] IKComponents;
void Start() {
// Register to get a call from PuppetMaster
puppetMaster.OnRead += OnRead;
// Take control of updating IK solvers
foreach (IK ik in IKComponents) ik.enabled = false;
}
void OnRead() {
if (!enabled) return;
// Solve IK before PuppetMaster reads the pose of the character
foreach (IK ik in IKComponents) ik.GetIKSolver().Update();
}
// Cleaning up the delegates
void OnDestroy() {
if (puppetMaster != null) {
puppetMaster.OnRead -= OnRead;
}
}
\endcode
<b>IK After Physics:</b>
Each frame PuppetMaster is done solving and mapping the Target character to the ragdoll, we have a chance to make minor adjustments (that don't change the physics anymore) to the character pose.
This can be useful for example when making sure hands are perfectly fixed to some points or doing aiming correction with AimIK.
Unity's built-in IK can not be applied after PuppetMaster has mapped the Target character to the ragdoll pose.
Final IK components can be updated whenever necessary and in this case we need to do it in the PuppetMaster.OnWrite delegate:
\code
public PuppetMaster puppetMaster;
public IK[] IKComponents;
void Start() {
// Register to get some calls from PuppetMaster
puppetMaster.OnWrite += OnWrite;
// Take control of updating IK solvers
foreach (IK ik in IKComponents) ik.enabled = false;
}
// PuppetMaster calls this when it is done mapping the animated character to the ragdoll so if we can apply our kinematic adjustments to it now
void OnWrite() {
if (!enabled) return;
// Solve IK after PuppetMaster writes the solved pose on the animated character.
foreach (IK ik in IKComponents) ik.GetIKSolver().Update();
}
// Cleaning up the delegates
void OnDestroy() {
if (puppetMaster != null) {
puppetMaster.OnWrite -= OnWrite;
}
}
\endcode
*/
/*! \page page8 Performance
* @todo Description of optimization techniques, PuppetMasterSettings.cs.
<b>Tips for improving the performance</b>
<br>
- Decrease PuppetMaster "Solver Iteration Count" (changes Rigidbody.solverIterationCount for all the muscles) to the minimum that you can work with. Less solver iterations makes the muscles weaker so you might have to increase PuppetMaster "Muscle Spring".
- "Fix Target Transforms" should be switched off when your character is animated at all times.
- "Visualize Target Pose" costs some performance in the Editor, but not in the built game.
- Leaving "Update Joint Anchors" off improves performance with the cost of simulation accuracy.
- "Angular Limits" and "Internal Collisions" reduce the workload on the physics engine when disabled.
- When using BehaviourPuppet, increase PuppetMaster "Collision Threshold". It determines how strong the collisions must be in order to be processed by the BehaviourPuppet, however, increasing the value will make the puppet's behaviour jerkier on collision.
- Reduce the number of muscles. Do you absolutely need 3 spine muscles or the feet or hand muscles?
- Reducing "Default Contact Offset" in the Physics settings reduces expensive OnCollisionStay broadcasts when using BehaviourPuppet.
- Increase the "Fixed Timestep" in Project Settings/Time to the maximum tolerable value.
- Keep your puppets away from each other. Less collisions means much less work for both the Physics engine and the PuppetMaster.
- Set PuppetMaster mode to "Disabled" for puppets when they don't need any physics simulation.
- Set PuppetMaster mode to "Kinematic" for puppets that only need the colliders for collision detection or raycasting.
- When you do not need to use any Puppet Behaviours nor get a call in case of collisions, comment out the OnCollisionEnter/Stay/Exit functions in MuscleCollisionBroadcaster.cs.
- PuppetMaster can also run a flat hierarchy ragdoll. Just right-click on the PuppetMaster header and select "Flatten Muscle Hierarchy" from the context menu.
* */
/*! \page page9 Behaviours
The Puppet Behaviours are classes that inherit from the abstract BehaviourBase.cs and that's main idea is to provide a pattern for developing functionalities that dynamically adjust muscle and pin weights, strength and other properties or make kinematic adjustments to the target pose.
The most important Puppet Behaviour is the BehaviourPuppet.cs that handles the pinning of Puppets to target animation, releasing those pins in case of collision and re-tightening them when getting up from the ground.
The Puppet Behaviours can be switched, for example when the BehaviourPuppet looses balance, it can theoretically switch to BehaviourCatchFall or BehaviourWindmill (both missing from the initial release, but will be developed in the future).
The Puppet Behaviours are designed so tha they would not contain a single external object reference. That means they can be simply duplicated and moved to another Puppet.
\image html Behaviours2.png
<b>Switching Behaviours:</b>
When working with multiple Behaviours, keep only the one that is supposed to run first enabled in the Editor.
For example when you have the BehaviourPuppet and BehaviourFall, keep the former enabled and the latter disabled if you wish for the Puppet to start from normal animated state, not falling.
Switching between behaviours by code must be done by calling <b>BehaviourBase.Activate();</b> on the Behaviour you wish to switch to. All other Behaviours will be disabled.
<b>Events</b>
Behaviours trigger events on certain occasions (such as losing balance). They can be used to get a message through to your own scripts or switching behaviours.
- <b>switchToBehaviour</b> - another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling.
- <b>animations</b> - animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade.
- <b>unityEvent</b> - the UnityEvent to invoke on this event.
\image html PuppetEvent.png
<b>Sub-Behaviours:</b>
Sub-behaviours are reusable self-contained chunks of functionaly that can be easily shared between multiple Puppet Behaviours.
For example SubBehaviourCOM is a module that automatically calculates and updates center of mass related information for the Puppet - data such as center or pressure, direction and angle of the COM vector and detect if the Puppet is grounded or not.
This prevents the necessity to duplicate code for all the Behaviours that need to make COM calculations.
To see how to use a sub-behaviour like that, take a look at the section below and the BehaviourTemplate.cs class.
<b>Creating Custom Behaviours:</b>
PuppetMaster has been built from start up with customization and extendibility in mind.
To create reusable behaviours of your own, make a class that extends the BehaviourBase abstract class or just make a copy or BehaviourTemplate.cs
and start adding functionality following the pattern at hand.
*/
/*! \page page10 BehaviourPuppet
The BehaviourPuppet handles pinning and unpinning puppets when they collide with objects or are hit via code, also automates getting up from an unbalanced state.
\image html Puppet.gif
<b>Getting Started</b>
- Copy the entire gameobject of the BehaviourPuppet from the demo character in "Melee" scene to your own Puppet (parent to the Behaviours root).
- Collision resistance depends on many things, also the mass of your Rigidbodies, if the Puppet is too easy or difficult to unbalance, tweak the "Collision Resistance" value first.
<b>Troubleshooting</b>
- <b>The Puppet never falls over, has "snake feet"</b> - decrease "Collision Resistance".
- <b>The Puppet loses balance on slightest contact</b> - increase "Collision Resistance" and/or "Regain Pin Speed". Increase "Knock Out Distance".
- <b>The Puppet tries to get up, but repeatedly fails</b> - increase "Get Up Collision Resistance" and/or "Get Up Regain Pin Speed Mlp" and/or "Get Up Knock Out Distance".
- <b>The Puppet's muscles are too stiff when unbalanced</b> - decrease "Unpinned Muscle Weight Mlp".
- <b>The Puppet doesn't lose balance when hit hard to the legs</b> - find the group override for the "Hips" and "Leg" and the "Foot" group. Increasing "Unping Parents", "Unpin Children" and "Unpin Group" makes the collisions propagate more heavily to the other body parts. Also try decreasing "Knock Out Distance".
<b>Collision And Recovery</b>
- <b>normalMode</b> - how does the puppet behave when currently not in contact with anything? Active mode keeps the PuppetMaster Active and mapped at all times. Unmapped blends out mapping to maintain 100% animation quality. Kenamatic keeps the PuppetMaster in Kinematic mode until there is a collision.
- <b>mappingBlendSpeed</b> - the speed of blending in mapping in case of contact when in Unmapped normal mode.
- <b>activateOnStaticCollisions</b> - if false, static colliders will not activate the puppet when they collide with the muscles. Note that the static colliders need to have a kinematic Rigidbody attached for this to work. Used only in Kinematic normal mode.
- <b>activateOnImpulse</b> - minimum collision impulse for activating the puppet. Used only in Kinematic normal mode.
- <b>groundLayers</b> - the layers that the character controller will be grounded to when unpinned or getting up.
- <b>collisionLayers</b> - the layers that will unpin the Puppet on collision.
- <b>collisionThreshold</b> - an optimization. The minimum square magnitude of the impulse that will be processed.
- <b>collisionResistance</b> - smaller value means more unpinning from collisions so the characters get knocked out more easily. If using a curve, the value will be evaluated by each muscle's target velocity magnitude. This can be used to make collision resistance higher while the character moves or animates faster.
- <b>collisionResistanceMultipliers</b> - used for multiplying the value of collision resistance based on the layer that collided with the Puppet.
- <b>maxCollisions</b> - and optimization. The maximum number of collisions that will be processed per physics step. Helps to avoid peaks.
- <b>regainPinSpeed</b> - how fast will the muscles of this group regain their pin weight?
- <b>muscleRelativeToPinWeight</b> - Muscle weight multiplier relative to pin weight. It can be used to make muscles weaker/stronger when they are more/less unpinned while in the normal Puppet state.
- <b>boostFalloff</b> - Boosting is a term used for making muscles temporarily immune to collisions and/or deal more damage to the muscles of other characters. That is done by increasing Muscle.State.immunity and Muscle.State.impulseMlp. For example when you set muscle.state.immunity to 1, boostFalloff will determine how fast this value will fall back to normal (0). Use BehaviourPuppet.BoostImmunity() and BehaviourPuppet.BoostImpulseMlp() for boosting from your own scripts. It is helpful for making the puppet stronger and deliever more punch while playing a melee hitting/kicking animation.
<b>Muscle Group Properties</b>
- <b>defaults</b> - the default muscle properties. If there are no 'Group Overrides', this will be used for all muscles.
<BR><b>unpinParents</b> - how much will collisions with muscles of this group unpin parent muscles?
<BR><b>unpinChildren</b> - how much will collisions with muscles of this group unpin child muscles?
<BR><b>unpinGroup</b> - how much will collisions with muscles of this group unpin muscles of the same group?
<BR><b>minMappingWeight</b> - if 1, muscles of this group will always be mapped to the ragdoll.
<BR><b>maxMappingWeight</b> - if 0, muscles of this group will not be mapped to the ragdoll pose even if they are unpinned.
<BR><b>disableColliders</b> - if true, muscles of this group will have their colliders disabled while in puppet state (not unbalanced nor getting up).
<BR><b>regainPinSpeed</b> - how fast will muscles of this group regain their pin weight (multiplier)?
<BR><b>collisionResistance</b> - smaller value means more unpinning from collisions (multiplier).
<BR><b>knockOutDistance</b> - if the distance from the muscle to it's target is larger than this value, the character will be knocked out.
<BR><b>puppetMaterial</b> - the PhysicsMaterial applied to the muscles while the character is in Puppet or GetUp state. Using a lower friction material reduces the risk of muscles getting stuck and pulled out of their joints.
<BR><b>unpinnedMaterial</b> - the PhysicsMaterial applied to the muscles while the character is in Unpinned state.
- <b>groupOverrides</b> - overriding default muscle properties for some muscle groups (for example making the feet stiffer or the hands looser).
<b>Losing Balance</b>
- <b>knockOutDistance</b> - if the distance from the muscle to it's target is larger than this value, the character will be knocked out.
- <b>unpinnedMuscleWeightMlp</b> - smaller value makes the muscles weaker when the puppet is knocked out.
- <b>dropProps</b> - if true, all muscles of the 'Prop' group will be detached from the puppet when it loses balance.
<b>Getting Up</b>
- <b>canGetUp</b> - if true, GetUp state will be triggerred automatically after 'Get Up Delay' and when the velocity of the hip muscle is less than 'Max Get Up Velocity'.
- <b>getUpDelay</b> - minimum delay for getting up after loosing balance. After that time has passed, will wait for the velocity of the hip muscle to come down below 'Max Get Up Velocity' and then switch to the GetUp state.
- <b>blendToAnimationTime</b> - the duration of blending the animation target from the ragdoll pose to the getting up animation once the GetUp state has been triggered.
- <b>maxGetUpVelocity</b> - will not get up before the velocity of the hip muscle has come down to this value.
- <b>minGetUpDuration</b> - will not get up before this amount of time has passed since loosing balance.
- <b>getUpCollisionResistanceMlp</b> - collision resistance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpRegainPinSpeedMlp</b> - regain pin weight speed multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpKnockOutDistanceMlp</b> - knock out distance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
- <b>getUpOffsetProne</b> - offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a prone pose. Tweak this value if your character slides a bit when starting to get up.
- <b>getUpOffsetSupine</b> - offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a supine pose. Tweak this value if your character slides a bit when starting to get up.
<b>Events</b>
- <b>onGetUpProne</b> - called when the character starts getting up from a prone pose (facing down).
- <b>onGetUpSupine</b> - called when the character starts getting up from a supine pose (facing up).
- <b>onLoseBalance</b> - called when the character is knocked out (loses balance). Doesn't matter from which state.
- <b>onLoseBalanceFromPuppet</b> - called when the character is knocked out (loses balance) only from the normal Puppet state.
- <b>onLoseBalanceFromGetUp</b> - called when the character is knocked out (loses balance) only from the GetUp state.
- <b>onRegainBalance</b> - called when the character has fully recovered and switched to the Puppet state.
\image html BehaviourPuppet.png
* */
/*! \page page11 BehaviourFall
BehaviourFall simply blends between two animation clips in a blend tree depending on the height of the ragdoll from the ground.
As seen from the gif below, when the ragdoll is high above the ground surface, a writhering animation is played, but when it falls down, a protective pose is blended in.
\image html Falling.gif
BehaviourFall requires for the Animator of the character to have a blend tree set up like in the image below.
You can copy the blend tree from the AnimatorController in the "Falling" demo scene.
\image html BehaviourFallAnimator.png
<b>Component Variables</b>
- <b>stateName</b> - Animation State to crossfade to when this behaviour is activated.
- <b>transitionDuration</b> - the duration of crossfading to stateName. Value is in seconds.
- <b>layer</b> - layer index containing the destination state. If no layer is specified or layer is -1, the first state that is found with the given name or hash will be played.
- <b>fixedTime</b> - start time of the current destination state. Value is in seconds. If no explicit fixedTime is specified or fixedTime value is float.NegativeInfinity, the state will either be played from the start if it's not already playing, or will continue playing from its current time and no transition will happen.
- <b>raycastLayers</b> - the layers that will be raycasted against to find colliding objects.
- <b>blendParameter</b> - the parameter in the Animator that blends between catch fall and writhe animations.
- <b>writheHeight</b> - the height of the pelvis from the ground at which will blend to writhe animation.
- <b>writheYVelocity</b> - the vertical velocity of the pelvis at which will blend to writhe animation.
- <b>blendSpeed</b> - the speed of blendig between the two falling animations.
- <b>canEnd</b> - if false, this behaviour will never end.
- <b>minTime</b> - the minimum time since this behaviour activated before it can end.
- <b>maxEndVelocity</b> - if the velocity of the pelvis falls below this value, can end the behaviour.
- <b>onEnd</b> - event triggered when all end conditions are met.
\image html BehaviourFall.png
* */
/*! \page page12 Baker
Baker is a universal tool for recording Humanoid, Generic and Legacy animation clips. Baker.cs is an abstract base class extended by HumanoidBaker.cs and GenericBaker.cs.
<BR>
<b>Baker allows you to:</b>
- Edit animation clips
- bake IK into animation
- combine animation layers
- bake InteractionSystem interactions
- bake ragdoll physics
- blend ragdoll physics with animation (PuppetMaster)
- bake Timeline
- fix Humanoid retargeting problems (hand, foot positions)
- bake outsourced Humanoid animation to specific character model to avoid using Foot IK for performance
- bake motion capture
- reduce animation memory footprint with Baker's advanced keyframe reduction tools
<b>Getting started:</b>
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/uakZqX1hju0" frameborder="0" allowfullscreen></iframe>\endhtmlonly
- Add the HumanoidBaker or GenericBaker component to the same GameObject as your character's Animator.
- Click on the button beneath "Save To Folder" to choose a folder for the baked animation clips.
- Play the scene.
- Click on the bake button.
<b>Animation Clips Mode</b>
<BR>AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController.
<BR>Set the Baker to "Animation Clips" mode and add some animation clips to the "Animation Clips" array. "Append Name" is a string that will be added to each clip's name for the saved clip. For example if your animation clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
<b>Animation States Mode</b>
<BR>AnimationStates mode can be used to bake a batch of Mecanim Animation States. This is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim.
<BR>Set the Baker to "Animation States" mode and add the Animation State names (only from the base layer) you wish to bake to the "Animation States" array. "Append Name" is a string that will be added to each state's name for the saved clip. For example if your animation state names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
<b>Playable Director Mode</b>
<BR>Bakes a PlayableDirector with a Timeline asset. Set the Baker to "Playable Director" mode and make sure the GameObject has a valid PlayableDirector.
<b>Realtime Mode</b>
<BR>Useful for baking an arbitrary range of animation, such as ragdoll simulation or an InteractionSystem interaction, in real-time.
\code
using RootMotion;
public class MyBakingTool {
public Baker baker;
public float bakeDuration = 5f;
void Start()
{
baker.mode = Baker.Mode.Realtime;
StartCoroutine(BakeDuration(bakeDuration));
}
private IEnumerator BakeDuration(float duration)
{
baker.StartBaking();
yield return new WaitForSeconds(duration);
baker.StopBaking();
}
}
\endcode
<b>Keyframe Reduction</b>
<BR> While developing a mobile game and running low on RAM, the quality of your animation will suffer a lot should you try to increase the keyframe reduction error thresholds in animation import settings.
The most noticable problem will be with the feet starting to float around in idle animations as there are not enough keyframes to make them appear properly planted. Idle animations are also usually the longest and most memory consuming.
Unity actually already contains a solution for this problem, but it is simply not implemented in the keyframe reduction options. That solution is the humanoid "Foot IK" system ("Foot IK" toggle in the Animator, previewable by enabling the "IK" toggle in the Animation Preview Window), that is normally used for fixing Humanoid retargeting problems.
Foot IK works by storing position and rotation channels of the foot bottoms from the original animation clip, then running a pass of IK on the legs of the retargeted character (that has different leg bone lenghts) to properly plant the feet.
Unity keyfame reduction options do not allow you to define different parameters for those IK curves and so they will be reduced just the same as the muscle channels, causing the feet to float even if you had "Foot IK" enabled.
Baker allows you define "Key Reduction Error" and "IK Key Reduction Error" separately, hence apply extreme key reduction to muscle channels that take most of the memory while maintaining normal reduction for the IK channels.
It also allows you to bake muscle channels at a lower frame rate than the IK channels by increasing the value of "Muscle Frame Rate Div". Those options can help you achieve better animation quality for a memory cost that is multiple times lower.
The same technique can be used for hand IK, making sure your 2-handed prop animations do not suffer from keyframe reduction.
\htmlonly <iframe width="854" height="480" src="https://www.youtube.com/embed/sH7OnpOQCg8" frameborder="0" allowfullscreen></iframe>\endhtmlonly
<b>Changing AnimationClipSettings</b>
<BR> When you first bake an animation clip, Baker will apply the default settings. If you modified the settings of the animation clip manually and baked again, Baker will maintain those modified settings so you will not have to apply them again.
<b>HumanoidBaker variables</b>
- <b>frameRate</b> - in AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
- <b>keyReductionError</b> - maximum allowed error for keyframe reduction.
- <b>IKKeyReductionError</b> - max keyframe reduction error for the Root.Q/T, LeftFoot IK and RightFoot IK channels. Having a larger error value for 'Key Reduction Error' and a smaller one for this enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
- <b>muscleFrameRateDiv</b> - frame rate divider for the muscle curves. If you had 'Frame Rate' set to 30, and this value set to 3, the muscle curves will be baked at 10 fps. Only the Root Q/T and Hand and Foot IK curves will be baked at 30. This enables you to optimize clip data size without the floating feet effect by enabling 'Foot IK' in the Animator.
- <b>bakeHandIK</b> - should the hand IK curves be added to the animation? Disable this if the original hand positions are not important when using the clip on another character via Humanoid retargeting.
- <b>mode</b> - AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
- <b>loop</b> - sets the baked animation clip to loop time and matches the last frame keys with the first. Note that when overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
- <b>animationClips</b> - AnimationClips to bake.
- <b>animationStates</b> - the name of the AnimationStates (must be on the base layer) to bake in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
- <b>appendName</b> - string that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
- <b>saveToFolder</b> - the folder to save the baked AnimationClips to.
\image html HumanoidBakerComponent.png
<b>GenericBaker variables</b>
- <b>frameRate</b> - in AnimationClips, AnimationStates or PlayableDirector mode - the frame rate at which the animation clip will be sampled. In Realtime mode - the frame rate at which the pose will be sampled. With the latter, the frame rate is not guaranteed if the player is not able to reach it.
- <b>keyReductionError</b> - maximum allowed error for keyframe reduction.
- <b>markAsLegacy</b> - if true, produced AnimationClips will be marked as Legacy and usable with the Legacy animation system.
- <b>root</b> - root Transform of the hierarchy to bake.
- <b>rootNode</b> - root node used for root motion.
- <b>ignoreList</b> - list of Transforms to ignore, rotation curves will not be baked for these Transforms.
- <b>bakePositionList</b> - localPosition curves will be baked for these Transforms only. If you are baking a character, the pelvis bone should be added to this array.
- <b>mode</b> - AnimationClips mode can be used to bake a batch of AnimationClips directly without the need of setting up an AnimatorController. AnimationStates mode is useful for when you need to set up a more complex rig with layers and AvatarMasks in Mecanim. PlayableDirector mode bakes a Timeline. Realtime mode is for continuous baking of gameplay, ragdoll phsysics or PuppetMaster dynamics.
- <b>loop</b> - sets the baked animation clip to loop time and matches the last frame keys with the first. Note that if you are overwriting a previously baked clip, AnimationClipSettings will be copied from the existing clip.
- <b>animationClips</b> - AnimationClips to bake.
- <b>animationStates</b> - the name of the AnimationStates (must be on the base layer) to bake in the Animator (Right-click on this component header and select 'Find Animation States' to have Baker fill those in automatically, required that state names match with the names of the clips used in them).
- <b>appendName</b> - string that will be added to each clip or animation state name for the saved clip. For example if your animation state/clip names were 'Idle' and 'Walk', then with '_Baked' as Append Name, the Baker will create 'Idle_Baked' and 'Walk_Baked' animation clips.
- <b>saveToFolder</b> - the folder to save the baked AnimationClips to.
\image html GenericBakerComponent.png
<b>Script References:</b>
- <a href="http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_humanoid_baker.html">HumanoidBaker</a>
- <a href="http://www.root-motion.com/finalikdox/html/class_root_motion_1_1_generic_baker.html">GenericBaker</a>
*/
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7dd9c3221309c480d990fa8a4cb04dc9
timeCreated: 1443523392
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: bb15b348b0d61a14f83b5ae527112c60
folderAsset: yes
timeCreated: 1444732416
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

@@ -1,57 +0,0 @@
fileFormatVersion: 2
guid: 5f77f33a83efd35429c7eb5dc9474f43
timeCreated: 1444738226
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: 4
maxTextureSize: 128
textureSettings:
filterMode: -1
aniso: 16
mipBias: -1
wrapMode: 1
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 1
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

@@ -1,57 +0,0 @@
fileFormatVersion: 2
guid: 1b10303a9012d794dbcd05b1f7f818bb
timeCreated: 1444737922
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: 4
maxTextureSize: 128
textureSettings:
filterMode: -1
aniso: 16
mipBias: -1
wrapMode: 1
nPOTScale: 1
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 1
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

@@ -1,57 +0,0 @@
fileFormatVersion: 2
guid: 8894e7b9cd0dd9a4b945ffc044647939
timeCreated: 1444732416
licenseType: Store
TextureImporter:
fileIDToRecycleName: {}
serializedVersion: 2
mipmaps:
mipMapMode: 0
enableMipMap: 0
linearTexture: 0
correctGamma: 0
fadeOut: 0
borderMipMap: 0
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 0
cubemapConvolution: 0
cubemapConvolutionSteps: 8
cubemapConvolutionExponent: 1.5
seamlessCubemap: 0
textureFormat: 4
maxTextureSize: 128
textureSettings:
filterMode: 1
aniso: 16
mipBias: -1
wrapMode: 1
nPOTScale: 0
lightmap: 0
rGBM: 0
compressionQuality: 50
allowsAlphaSplitting: 0
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaIsTransparency: 1
textureType: 5
buildTargetSettings: []
spriteSheet:
sprites: []
outline: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 7c3f0c0760e2640de90e23737ee45894
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,13 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!134 &13400000
PhysicMaterial:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: CharacterController
dynamicFriction: 0
staticFriction: 0
bounciness: 0
frictionCombine: 0
bounceCombine: 0
@@ -1,4 +0,0 @@
fileFormatVersion: 2
guid: 11f2d11e5774f4c7e87f5d8568a243f1
NativeFormatImporter:
userData:
@@ -1,13 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!134 &13400000
PhysicMaterial:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Feet
dynamicFriction: 0
staticFriction: 0
bounciness: 0
frictionCombine: 0
bounceCombine: 0
@@ -1,4 +0,0 @@
fileFormatVersion: 2
guid: a1e3ef68e2c78461089ab56644e6b319
NativeFormatImporter:
userData:
@@ -1,13 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!134 &13400000
PhysicMaterial:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Puppet
dynamicFriction: 0.1
staticFriction: 0.3
bounciness: 0
frictionCombine: 0
bounceCombine: 0
@@ -1,4 +0,0 @@
fileFormatVersion: 2
guid: 6d32fedfdb4984e6abc6a0e91980d57a
NativeFormatImporter:
userData:
@@ -1,13 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!134 &13400000
PhysicMaterial:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Unpinned
dynamicFriction: 0.4
staticFriction: 0.4
bounciness: 0
frictionCombine: 0
bounceCombine: 0
@@ -1,4 +0,0 @@
fileFormatVersion: 2
guid: d4563de398e2c4412a95f4317ddf4b1a
NativeFormatImporter:
userData:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 87baf8fa5423a4a34a8b37e2daeb126b
folderAsset: yes
timeCreated: 1452077007
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 1dff093be4db04b4598ba83e34059d41
folderAsset: yes
timeCreated: 1452077127
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,78 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &115442
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
serializedVersion: 5
m_Component:
- component: {fileID: 464076}
- component: {fileID: 11446532}
m_Layer: 0
m_Name: Fall
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &464076
Transform:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 115442}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &11446532
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 115442}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 367e952422ba44b82a0206d3b9cf12c4, type: 3}
m_Name:
m_EditorClassIdentifier:
puppetMaster: {fileID: 0}
deactivated: 0
stateName: Falling
transitionDuration: 0.7
layer: 0
fixedTime: 0
raycastLayers:
serializedVersion: 2
m_Bits: 19
blendParameter: FallBlend
writheHeight: 2.5
writheYVelocity: 1
blendSpeed: 3
blendMappingSpeed: 1
canEnd: 1
minTime: 1
maxEndVelocity: 0.4
onEnd:
switchToBehaviour: BehaviourPuppet
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
--- !u!1001 &100100000
Prefab:
m_ObjectHideFlags: 1
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications: []
m_RemovedComponents: []
m_ParentPrefab: {fileID: 0}
m_RootGameObject: {fileID: 115442}
m_IsPrefabParent: 1
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 1549100322cdb4b80b441323f4142fce
timeCreated: 1452174521
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,276 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &167430
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
serializedVersion: 5
m_Component:
- component: {fileID: 444240}
- component: {fileID: 11466454}
m_Layer: 8
m_Name: Puppet (with Fall)
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &444240
Transform:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 167430}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &11466454
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 167430}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 1efacf79ab4214e85aeebfd07064c20f, type: 3}
m_Name:
m_EditorClassIdentifier:
puppetMaster: {fileID: 0}
deactivated: 0
masterProps:
normalMode: 1
mappingBlendSpeed: 15
activateOnStaticCollisions: 0
activateOnImpulse: 0
groundLayers:
serializedVersion: 2
m_Bits: 16
collisionLayers:
serializedVersion: 2
m_Bits: 3
collisionThreshold: 0
collisionResistance:
mode: 0
floatValue: 700
curve:
serializedVersion: 2
m_Curve:
- serializedVersion: 2
time: 0
value: 56.68847
inSlope: 0
outSlope: 0
tangentMode: 0
- serializedVersion: 2
time: 5.1236973
value: 140.30418
inSlope: 0
outSlope: 0
tangentMode: 0
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
tooltip: Smaller value means more unpinning from collisions so the characters
get knocked out more easily. If using a curve, the value will be evaluated by
each muscle's target velocity magnitude. This can be used to make collision
resistance higher while the character moves or animates faster.
collisionResistanceMultipliers: []
maxCollisions: 30
regainPinSpeed: 1
boostFalloff: 1
defaults:
unpinParents: 0.9
unpinChildren: 0.9
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 1
puppetMaterial: {fileID: 13400000, guid: a3fd0ffcf0d0a384ba3568687a96ab8e, type: 2}
unpinnedMaterial: {fileID: 13400000, guid: d4563de398e2c4412a95f4317ddf4b1a, type: 2}
groupOverrides:
- name: Head
groups: 02000000
props:
unpinParents: 0.9
unpinChildren: 0
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Arm, Hand, Prop
groups: 030000000400000008000000
props:
unpinParents: 0.5
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 100
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Hips, Leg
groups: 0000000005000000
props:
unpinParents: 0.9
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1.5
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Foot
groups: 06000000
props:
unpinParents: 1
unpinChildren: 0
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 2
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Prop
groups: 08000000
props:
unpinParents: 0.5
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 1
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 4
collisionResistance: 1
knockOutDistance: 100
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
knockOutDistance: 1.5
unpinnedMuscleWeightMlp: 0.4
maxRigidbodyVelocity: 7
pinWeightThreshold: 1
unpinnedMuscleKnockout: 1
dropProps: 0
canGetUp: 1
getUpDelay: 0
blendToAnimationTime: 0.3
maxGetUpVelocity: 0.4
minGetUpDuration: 1.5
getUpCollisionResistanceMlp: 2
getUpRegainPinSpeedMlp: 1
getUpKnockOutDistanceMlp: 1
getUpOffsetProne: {x: 0, y: 0, z: 0}
getUpOffsetSupine: {x: 0, y: 0, z: 0}
onGetUpProne:
switchToBehaviour:
animations:
- animationState: GetUpProne
crossfadeTime: 0.2
layer: 0
resetNormalizedTime: 1
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onGetUpSupine:
switchToBehaviour:
animations:
- animationState: GetUpSupine
crossfadeTime: 0.2
layer: 0
resetNormalizedTime: 1
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalance:
switchToBehaviour: BehaviourFall
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalanceFromPuppet:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalanceFromGetUp:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onRegainBalance:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
canMoveTarget: 1
--- !u!1001 &100100000
Prefab:
m_ObjectHideFlags: 1
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 0}
propertyPath: masterProps.mappingBlendSpeed
value: 15
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: defaults.puppetMaterial
value:
objectReference: {fileID: 13400000, guid: a3fd0ffcf0d0a384ba3568687a96ab8e,
type: 2}
- target: {fileID: 0}
propertyPath: defaults.unpinnedMaterial
value:
objectReference: {fileID: 13400000, guid: d4563de398e2c4412a95f4317ddf4b1a,
type: 2}
- target: {fileID: 0}
propertyPath: unpinnedMuscleWeightMlp
value: .400000006
objectReference: {fileID: 0}
m_RemovedComponents: []
m_ParentPrefab: {fileID: 0}
m_RootGameObject: {fileID: 167430}
m_IsPrefabParent: 1
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: bdc15cb97660141638eaeea7afbe7591
timeCreated: 1452174511
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,304 +0,0 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &167430
GameObject:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
serializedVersion: 5
m_Component:
- component: {fileID: 444240}
- component: {fileID: 11466454}
m_Layer: 8
m_Name: Puppet
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &444240
Transform:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 167430}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &11466454
MonoBehaviour:
m_ObjectHideFlags: 1
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 100100000}
m_GameObject: {fileID: 167430}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 1efacf79ab4214e85aeebfd07064c20f, type: 3}
m_Name:
m_EditorClassIdentifier:
puppetMaster: {fileID: 0}
deactivated: 0
masterProps:
normalMode: 1
mappingBlendSpeed: 15
activateOnStaticCollisions: 0
activateOnImpulse: 0
groundLayers:
serializedVersion: 2
m_Bits: 16
collisionLayers:
serializedVersion: 2
m_Bits: 3
collisionThreshold: 0
collisionResistance:
mode: 0
floatValue: 700
curve:
serializedVersion: 2
m_Curve:
- serializedVersion: 2
time: 0
value: 56.68847
inSlope: 0
outSlope: 0
tangentMode: 0
- serializedVersion: 2
time: 5.1236973
value: 140.30418
inSlope: 0
outSlope: 0
tangentMode: 0
m_PreInfinity: 2
m_PostInfinity: 2
m_RotationOrder: 4
tooltip: Smaller value means more unpinning from collisions so the characters
get knocked out more easily. If using a curve, the value will be evaluated by
each muscle's target velocity magnitude. This can be used to make collision
resistance higher while the character moves or animates faster.
collisionResistanceMultipliers: []
maxCollisions: 30
regainPinSpeed: 1
boostFalloff: 1
defaults:
unpinParents: 0.9
unpinChildren: 0.9
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 1
puppetMaterial: {fileID: 13400000, guid: a3fd0ffcf0d0a384ba3568687a96ab8e, type: 2}
unpinnedMaterial: {fileID: 13400000, guid: d4563de398e2c4412a95f4317ddf4b1a, type: 2}
groupOverrides:
- name: Head
groups: 02000000
props:
unpinParents: 0.9
unpinChildren: 0
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Arm, Hand, Prop
groups: 030000000400000008000000
props:
unpinParents: 0.5
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1
collisionResistance: 1
knockOutDistance: 100
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Hips, Leg
groups: 0000000005000000
props:
unpinParents: 0.9
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 1.5
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Foot
groups: 06000000
props:
unpinParents: 1
unpinChildren: 0
unpinGroup: 0
minMappingWeight: 0
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 2
collisionResistance: 1
knockOutDistance: 0.6
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
- name: Prop
groups: 08000000
props:
unpinParents: 0.5
unpinChildren: 1
unpinGroup: 0
minMappingWeight: 1
maxMappingWeight: 1
minPinWeight: 0
disableColliders: 0
regainPinSpeed: 4
collisionResistance: 1
knockOutDistance: 100
puppetMaterial: {fileID: 0}
unpinnedMaterial: {fileID: 0}
knockOutDistance: 1.5
unpinnedMuscleWeightMlp: 0.4
maxRigidbodyVelocity: 10
pinWeightThreshold: 1
unpinnedMuscleKnockout: 1
dropProps: 0
canGetUp: 1
getUpDelay: 1
blendToAnimationTime: 0.3
maxGetUpVelocity: 0.4
minGetUpDuration: 1.5
getUpCollisionResistanceMlp: 2
getUpRegainPinSpeedMlp: 1
getUpKnockOutDistanceMlp: 1
getUpOffsetProne: {x: 0, y: 0, z: 0}
getUpOffsetSupine: {x: 0, y: 0, z: 0}
onGetUpProne:
switchToBehaviour:
animations:
- animationState: GetUpProne
crossfadeTime: 0.2
layer: 0
resetNormalizedTime: 1
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onGetUpSupine:
switchToBehaviour:
animations:
- animationState: GetUpSupine
crossfadeTime: 0.2
layer: 0
resetNormalizedTime: 1
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalance:
switchToBehaviour:
animations:
- animationState: Fall
crossfadeTime: 0.7
layer: 0
resetNormalizedTime: 0
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalanceFromPuppet:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onLoseBalanceFromGetUp:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
onRegainBalance:
switchToBehaviour:
animations: []
unityEvent:
m_PersistentCalls:
m_Calls: []
m_TypeName: UnityEngine.Events.UnityEvent, UnityEngine.CoreModule, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=null
canMoveTarget: 1
--- !u!1001 &100100000
Prefab:
m_ObjectHideFlags: 1
serializedVersion: 2
m_Modification:
m_TransformParent: {fileID: 0}
m_Modifications:
- target: {fileID: 0}
propertyPath: onLoseBalance.animations.Array.size
value: 1
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: masterProps.mappingBlendSpeed
value: 15
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: defaults.puppetMaterial
value:
objectReference: {fileID: 13400000, guid: a3fd0ffcf0d0a384ba3568687a96ab8e,
type: 2}
- target: {fileID: 0}
propertyPath: defaults.unpinnedMaterial
value:
objectReference: {fileID: 13400000, guid: d4563de398e2c4412a95f4317ddf4b1a,
type: 2}
- target: {fileID: 0}
propertyPath: unpinnedMuscleWeightMlp
value: .400000006
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: onLoseBalance.switchToBehaviour
value:
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: onLoseBalance.animations.Array.data[0].animationState
value: Fall
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: onLoseBalance.animations.Array.data[0].crossfadeTime
value: .699999988
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: getUpDelay
value: 1
objectReference: {fileID: 0}
- target: {fileID: 0}
propertyPath: groupOverrides.Array.data[3].props.disableColliders
value: 0
objectReference: {fileID: 0}
m_RemovedComponents: []
m_ParentPrefab: {fileID: 0}
m_RootGameObject: {fileID: 167430}
m_IsPrefabParent: 1
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: e19ae6787d767d749b846a5901016165
timeCreated: 1485251184
licenseType: Store
NativeFormatImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 7f3f69239b7b44730bcf22339d4fce07
timeCreated: 1449669765
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: c66aa931027064313b219c28f8c216c6
timeCreated: 1446126506
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 45eb4cc3199cf48388e0d2d7adaca558
timeCreated: 1446126425
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 0aeddeec36a3b4044b9037547f1d492a
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,14 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
public class AnimationBlocker : MonoBehaviour {
void LateUpdate()
{
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: e3269be4feb4a4269944c7ee3b1e8a03
timeCreated: 1471635392
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 76c75a8f1e2844d2bbd3bd4bb15ed08c
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,438 +0,0 @@
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
namespace RootMotion.Dynamics
{
/// <summary>
/// The base abstract class for all Puppet Behaviours.
/// </summary>
public abstract class BehaviourBase : MonoBehaviour
{
/// <summary>
/// Gets the PuppetMaster associated with this behaviour. Returns null while the behaviour is not initiated by the PuppetMaster.
/// </summary>
[HideInInspector] public PuppetMaster puppetMaster;
public delegate void BehaviourDelegate();
public delegate void HitDelegate(MuscleHit hit);
public delegate void CollisionDelegate(MuscleCollision collision);
public abstract void OnReactivate();
public BehaviourDelegate OnPreActivate;
public BehaviourDelegate OnPreInitiate;
public BehaviourDelegate OnPreFixedUpdate;
public BehaviourDelegate OnPreUpdate;
public BehaviourDelegate OnPreLateUpdate;
//public BehaviourDelegate OnPreDisable;
public BehaviourDelegate OnPreDeactivate;
public BehaviourDelegate OnPreFixTransforms;
public BehaviourDelegate OnPreRead;
public BehaviourDelegate OnPreWrite;
public HitDelegate OnPreMuscleHit;
public CollisionDelegate OnPreMuscleCollision;
public CollisionDelegate OnPreMuscleCollisionExit;
public BehaviourDelegate OnHierarchyChanged;
public virtual void Resurrect() { }
public virtual void Freeze() { }
public virtual void Unfreeze() { }
public virtual void KillStart() { }
public virtual void KillEnd() { }
public virtual void OnTeleport(Quaternion deltaRotation, Vector3 deltaPosition, Vector3 pivot, bool moveToTarget) { }
public virtual void OnMuscleDisconnected(Muscle m) { }
public virtual void OnMuscleReconnected(Muscle m) { }
public virtual void OnMuscleAdded(Muscle m)
{
if (OnHierarchyChanged != null) OnHierarchyChanged();
}
public virtual void OnMuscleRemoved(Muscle m)
{
if (OnHierarchyChanged != null) OnHierarchyChanged();
}
protected virtual void OnActivate() { }
protected virtual void OnDeactivate() { }
protected virtual void OnInitiate() { }
protected virtual void OnFixedUpdate() { }
protected virtual void OnUpdate() { }
protected virtual void OnLateUpdate() { }
//protected virtual void OnDisableBehaviour() {}
protected virtual void OnDrawGizmosBehaviour() { }
protected virtual void OnFixTransformsBehaviour() { }
protected virtual void OnReadBehaviour() { }
protected virtual void OnWriteBehaviour() { }
protected virtual void OnMuscleHitBehaviour(MuscleHit hit) { }
protected virtual void OnMuscleCollisionBehaviour(MuscleCollision collision) { }
protected virtual void OnMuscleCollisionExitBehaviour(MuscleCollision collision) { }
public BehaviourDelegate OnPostActivate;
public BehaviourDelegate OnPostInitiate;
public BehaviourDelegate OnPostFixedUpdate;
public BehaviourDelegate OnPostUpdate;
public BehaviourDelegate OnPostLateUpdate;
//public BehaviourDelegate OnPostDisable;
public BehaviourDelegate OnPostDeactivate;
public BehaviourDelegate OnPostDrawGizmos;
public BehaviourDelegate OnPostFixTransforms;
public BehaviourDelegate OnPostRead;
public BehaviourDelegate OnPostWrite;
public HitDelegate OnPostMuscleHit;
public CollisionDelegate OnPostMuscleCollision;
public CollisionDelegate OnPostMuscleCollisionExit;
[HideInInspector] public bool deactivated;
public bool forceActive { get; protected set; }
private bool initiated = false;
public void Initiate()
{
initiated = true;
if (OnPreInitiate != null) OnPreInitiate();
OnInitiate();
if (OnPostInitiate != null) OnPostInitiate();
}
public void OnFixTransforms()
{
if (!initiated) return;
if (!enabled) return;
if (OnPreFixTransforms != null) OnPreFixTransforms();
OnFixTransformsBehaviour();
if (OnPostFixTransforms != null) OnPostFixTransforms();
}
public void OnRead()
{
if (!initiated) return;
if (!enabled) return;
if (OnPreRead != null) OnPreRead();
OnReadBehaviour();
if (OnPostRead != null) OnPostRead();
}
public void OnWrite()
{
if (!initiated) return;
if (!enabled) return;
if (OnPreWrite != null) OnPreWrite();
OnWriteBehaviour();
if (OnPostWrite != null) OnPostWrite();
}
public void OnMuscleHit(MuscleHit hit)
{
if (!initiated) return;
if (OnPreMuscleHit != null) OnPreMuscleHit(hit);
OnMuscleHitBehaviour(hit);
if (OnPostMuscleHit != null) OnPostMuscleHit(hit);
}
public void OnMuscleCollision(MuscleCollision collision)
{
if (!initiated) return;
if (OnPreMuscleCollision != null) OnPreMuscleCollision(collision);
OnMuscleCollisionBehaviour(collision);
if (OnPostMuscleCollision != null) OnPostMuscleCollision(collision);
}
public void OnMuscleCollisionExit(MuscleCollision collision)
{
if (!initiated) return;
if (OnPreMuscleCollisionExit != null) OnPreMuscleCollisionExit(collision);
OnMuscleCollisionExitBehaviour(collision);
if (OnPostMuscleCollisionExit != null) OnPostMuscleCollisionExit(collision);
}
void OnEnable()
{
if (!initiated)
{
// Discarding Unity's initial OnEnable call, because the starting behaviour will be determined by PuppetMaster
return;
}
Activate();
}
public void Activate()
{
foreach (BehaviourBase b in puppetMaster.behaviours)
{
b.enabled = b == this;
}
if (OnPreActivate != null) OnPreActivate();
OnActivate();
if (OnPostActivate != null) OnPostActivate();
}
void OnDisable()
{
if (!initiated) return;
if (OnPreDeactivate != null) OnPreDeactivate();
OnDeactivate();
if (OnPostDeactivate != null) OnPostDeactivate();
}
public void FixedUpdateB()
{
if (!initiated) return;
if (!enabled) return;
if (puppetMaster.muscles.Length <= 0) return;
if (OnPreFixedUpdate != null && enabled) OnPreFixedUpdate();
OnFixedUpdate();
if (OnPostFixedUpdate != null && enabled) OnPostFixedUpdate();
}
public void UpdateB()
{
if (!initiated) return;
if (!enabled) return;
if (puppetMaster.muscles.Length <= 0) return;
if (OnPreUpdate != null && enabled) OnPreUpdate();
OnUpdate();
if (OnPostUpdate != null && enabled) OnPostUpdate();
}
public void LateUpdateB()
{
if (!initiated) return;
if (!enabled) return;
if (puppetMaster.muscles.Length <= 0) return;
if (OnPreLateUpdate != null && enabled) OnPreLateUpdate();
OnLateUpdate();
if (OnPostLateUpdate != null && enabled) OnPostLateUpdate();
}
protected virtual void OnDrawGizmos()
{
if (!initiated) return;
OnDrawGizmosBehaviour();
if (OnPostDrawGizmos != null) OnPostDrawGizmos();
}
/// <summary>
/// Defines actions taken on certain events defined by the Puppet Behaviours.
/// </summary>
[System.Serializable]
public struct PuppetEvent
{
[TooltipAttribute("Another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling.")]
/// <summary>
/// Another Puppet Behaviour to switch to on this event. This must be the exact Type of the the Behaviour, careful with spelling.
/// </summary>
public string switchToBehaviour;
[TooltipAttribute("Animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade.")]
/// <summary>
/// Animations to cross-fade to on this event. This is separate from the UnityEvent below because UnityEvents can't handle calls with more than one parameter such as Animator.CrossFade.
/// </summary>
public AnimatorEvent[] animations;
[TooltipAttribute("The UnityEvent to invoke on this event.")]
/// <summary>
/// The UnityEvent to invoke on this event.
/// </summary>
public UnityEvent unityEvent;
public bool switchBehaviour
{
get
{
return switchToBehaviour != string.Empty && switchToBehaviour != empty;
}
}
private const string empty = "";
public void Trigger(PuppetMaster puppetMaster, bool switchBehaviourEnabled = true)
{
unityEvent.Invoke();
foreach (AnimatorEvent animatorEvent in animations) animatorEvent.Activate(puppetMaster.targetAnimator, puppetMaster.targetAnimation);
if (switchBehaviour)
{
bool found = false;
foreach (BehaviourBase behaviour in puppetMaster.behaviours)
{
//if (behaviour != null && behaviour.GetType() == System.Type.GetType(switchToBehaviour)) {
if (behaviour != null && behaviour.GetType().ToString() == "RootMotion.Dynamics." + switchToBehaviour)
{
found = true;
//behaviour.Activate();
behaviour.enabled = true;
break;
}
}
if (!found)
{
Debug.LogWarning("No Puppet Behaviour of type '" + switchToBehaviour + "' was found. Can not switch to the behaviour, please check the spelling (also for empty spaces).");
}
}
}
}
/// <summary>
/// Cross-fades to an animation state. UnityEvent can not be used for cross-fading, it requires multiple parameters.
/// </summary>
[System.Serializable]
public class AnimatorEvent
{
/// <summary>
/// The name of the animation state
/// </summary>
public string animationState;
/// <summary>
/// The crossfading time
/// </summary>
public float crossfadeTime = 0.3f;
/// <summary>
/// The layer of the animation state (if using Legacy, the animation state will be forced to this layer)
/// </summary>
public int layer;
/// <summary>
/// Should the animation always start from 0 normalized time?
/// </summary>
public bool resetNormalizedTime;
private const string empty = "";
// Activate the animation
public void Activate(Animator animator, Animation animation)
{
if (animator != null) Activate(animator);
if (animation != null) Activate(animation);
}
// Activate a Mecanim animation
private void Activate(Animator animator)
{
if (animationState == empty) return;
if (resetNormalizedTime)
{
if (crossfadeTime > 0f) animator.CrossFadeInFixedTime(animationState, crossfadeTime, layer, 0f);
else animator.Play(animationState, layer, 0f);
}
else
{
if (crossfadeTime > 0f)
{
animator.CrossFadeInFixedTime(animationState, crossfadeTime, layer);
}
else animator.Play(animationState, layer);
}
}
// Activate a Legacy animation
private void Activate(Animation animation)
{
if (animationState == empty) return;
if (resetNormalizedTime) animation[animationState].normalizedTime = 0f;
animation[animationState].layer = layer;
animation.CrossFade(animationState, crossfadeTime);
}
}
protected void RotateTargetToRootMuscle()
{
Vector3 hipsForward = Quaternion.Inverse(puppetMaster.muscles[0].target.rotation) * puppetMaster.targetRoot.forward;
Vector3 forward = puppetMaster.muscles[0].rigidbody.rotation * hipsForward;
forward.y = 0f;
puppetMaster.targetRoot.rotation = Quaternion.LookRotation(forward);
}
protected void TranslateTargetToRootMuscle(float maintainY)
{
puppetMaster.muscles[0].target.position = new Vector3(
puppetMaster.muscles[0].transform.position.x,
Mathf.Lerp(puppetMaster.muscles[0].transform.position.y, puppetMaster.muscles[0].target.position.y, maintainY),
puppetMaster.muscles[0].transform.position.z);
}
protected void RemovePropMuscles()
{
while (ContainsRemovablePropMuscle())
{
for (int i = 0; i < puppetMaster.muscles.Length; i++)
{
if (puppetMaster.muscles[i].props.group == Muscle.Group.Prop && !puppetMaster.muscles[i].isPropMuscle)
{
puppetMaster.RemoveMuscleRecursive(puppetMaster.muscles[i].joint, true);
break;
}
}
}
}
protected virtual void GroundTarget(LayerMask layers)
{
Ray ray = new Ray(puppetMaster.targetRoot.position + puppetMaster.targetRoot.up, -puppetMaster.targetRoot.up);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 4f, layers))
{
if (!float.IsNaN(hit.point.x) && !float.IsNaN(hit.point.y) && !float.IsNaN(hit.point.z))
{
puppetMaster.targetRoot.position = hit.point;
}
else
{
Debug.LogWarning("Raycasting against a large collider has produced a NaN hit point.", transform);
}
}
}
protected bool ContainsRemovablePropMuscle()
{
foreach (Muscle m in puppetMaster.muscles)
{
if (m.props.group == Muscle.Group.Prop && !m.isPropMuscle) return true;
}
return false;
}
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 01860b3861b7c4464b52da90d288bfea
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -1,227 +0,0 @@
using UnityEngine;
using System.Collections;
using RootMotion;
namespace RootMotion.Dynamics {
/// <summary>
/// Blends between two animation clips in a blend tree depending on the height of the ragdoll from the ground.
/// </summary>
[HelpURL("http://root-motion.com/puppetmasterdox/html/page11.html")]
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Behaviours/BehaviourFall")]
public class BehaviourFall : BehaviourBase {
// Open the User Manual URL
[ContextMenu("User Manual")]
void OpenUserManual() {
Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page11.html");
}
// Open the Script Reference URL
[ContextMenu("Scrpt Reference")]
void OpenScriptReference() {
Application.OpenURL("http://root-motion.com/puppetmasterdox/html/class_root_motion_1_1_dynamics_1_1_behaviour_fall.html");
}
[LargeHeader("Animation State")]
[Tooltip("Animation State to crossfade to when this behaviour is activated.")]
/// <summary>
/// Animation State to crosfade to when this behaviour is activated.
/// </summary>
public string stateName = "Falling";
[Tooltip("The duration of crossfading to 'State Name'. Value is in seconds.")]
/// <summary>
/// The duration of crossfading to "State Name". Value is in seconds.
/// </summary>
public float transitionDuration = 0.4f;
[Tooltip("Layer index containing the destination state. If no layer is specified or layer is -1, the first state that is found with the given name or hash will be played.")]
/// <summary>
/// Layer index containing the destination state. If no layer is specified or layer is -1, the first state that is found with the given name or hash will be played.
/// </summary>
public int layer;
[Tooltip("Start time of the current destination state. Value is in seconds. If no explicit fixedTime is specified or fixedTime value is float.NegativeInfinity, the state will either be played from the start if it's not already playing, or will continue playing from its current time and no transition will happen.")]
/// <summary>
/// Start time of the current destination state. Value is in seconds. If no explicit fixedTime is specified or fixedTime value is float.NegativeInfinity, the state will either be played from the start if it's not already playing, or will continue playing from its current time and no transition will happen.
/// </summary>
public float fixedTime;
[LargeHeader("Blending")]
[Tooltip("The layers that will be raycasted against to find colliding objects.")]
/// <summary>
/// The layers that will be raycasted against to find colliding objects.
/// </summary>
public LayerMask raycastLayers;
[Tooltip("The parameter in the Animator that blends between catch fall and writhe animations.")]
/// <summary>
/// The parameter in the Animator that blends between catch fall and writhe animations.
/// </summary>
public string blendParameter = "FallBlend";
[Tooltip("The height of the pelvis from the ground at which will blend to writhe animation.")]
/// <summary>
/// The height of the pelvis from the ground at which will blend to writhe animation.
/// </summary>
public float writheHeight = 4f;
[Tooltip("The vertical velocity of the pelvis at which will blend to writhe animation.")]
/// <summary>
/// The vertical velocity of the pelvis at which will blend to writhe animation.
/// </summary>
public float writheYVelocity = 1f;
[Tooltip("The speed of blendig between the two falling animations.")]
/// <summary>
/// The speed of blendig between the two falling animations.
/// </summary>
public float blendSpeed = 3f;
[Tooltip("The speed of blending in mapping on activation.")]
/// <summary>
/// The speed of blending in mapping on activation.
/// </summary>
public float blendMappingSpeed = 1f;
[LargeHeader("Ending")]
[Tooltip("If false, this behaviour will never end.")]
/// <summary>
/// If false, this behaviour will never end.
/// </summary>
public bool canEnd;
[Tooltip("The minimum time since this behaviour activated before it can end.")]
/// <summary>
/// The minimum time since this behaviour activated before it can end.
/// </summary>
public float minTime = 1.5f;
[Tooltip("If the velocity of the pelvis falls below this value, can end the behaviour.")]
/// <summary>
/// If the velocity of the pelvis falls below this value, can end the behaviour.
/// </summary>
public float maxEndVelocity = 0.5f;
[Tooltip("Event triggered when all end conditions are met.")]
/// <summary>
/// Event triggered when all end conditions are met.
/// </summary>
public PuppetEvent onEnd;
private float timer;
private bool endTriggered;
protected override void OnActivate() {
forceActive = true;
StopAllCoroutines();
StartCoroutine(SmoothActivate());
}
protected override void OnDeactivate() {
forceActive = false;
}
public override void OnReactivate() {
timer = 0f;
endTriggered = false;
}
// Making sure all params are smoothly blended, not jumping simultaneously
private IEnumerator SmoothActivate() {
timer = 0f;
endTriggered = false;
puppetMaster.targetAnimator.CrossFadeInFixedTime(stateName, transitionDuration, layer, fixedTime);
foreach (Muscle m in puppetMaster.muscles) {
m.state.pinWeightMlp = 0f;
m.rigidbody.velocity = m.mappedVelocity;
m.rigidbody.angularVelocity = m.mappedAngularVelocity;
}
float fader = 0f;
while (fader < 1f) {
fader += Time.deltaTime;
foreach (Muscle m in puppetMaster.muscles) {
m.state.pinWeightMlp -= Time.deltaTime;
m.state.mappingWeightMlp += Time.deltaTime * blendMappingSpeed;
}
yield return null;
}
}
protected override void OnFixedUpdate() {
if (raycastLayers == -1) Debug.LogWarning("BehaviourFall has no layers to raycast to.", transform);
// Blending between catch fall and writhe animations
float blendTarget = GetBlendTarget(GetGroundHeight());
float blend = Mathf.MoveTowards(puppetMaster.targetAnimator.GetFloat(blendParameter), blendTarget, Time.deltaTime * blendSpeed);
puppetMaster.targetAnimator.SetFloat(blendParameter, blend);
// Ending conditions
timer += Time.deltaTime;
if (!endTriggered && canEnd && timer >= minTime && !puppetMaster.isBlending && puppetMaster.muscles[0].rigidbody.velocity.magnitude < maxEndVelocity) {
endTriggered = true;
onEnd.Trigger(puppetMaster);
return;
}
}
protected override void OnLateUpdate() {
puppetMaster.targetRoot.position += puppetMaster.muscles[0].transform.position - puppetMaster.muscles[0].target.position;
GroundTarget(raycastLayers);
}
public override void Resurrect() {
foreach (Muscle m in puppetMaster.muscles) {
m.state.pinWeightMlp = 0f;
}
}
// 1 is writhe animation, 0 is catch fall
private float GetBlendTarget(float groundHeight) {
if (groundHeight > writheHeight) return 1f;
Vector3 verticalVelocity = V3Tools.ExtractVertical(puppetMaster.muscles[0].rigidbody.velocity, puppetMaster.targetRoot.up, 1f);
float velocityY = verticalVelocity.magnitude;
if (Vector3.Dot(verticalVelocity, puppetMaster.targetRoot.up) < 0f) velocityY = -velocityY;
if (velocityY > writheYVelocity) return 1f;
//if (puppetMaster.muscles[0].rigidbody.velocity.y > writheYVelocity) return 1f;
return 0f;
}
// Returns the height of the first muscle from the ground
private float GetGroundHeight() {
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(puppetMaster.muscles[0].rigidbody.position, -puppetMaster.targetRoot.up, out hit, 100f, raycastLayers)) {
return hit.distance;
}
return Mathf.Infinity;
}
public override void OnMuscleReconnected(Muscle m)
{
base.OnMuscleReconnected(m);
m.state.pinWeightMlp = 0f;
m.state.muscleWeightMlp = 1;
m.state.muscleDamperMlp = 1;
m.state.maxForceMlp = 1;
m.state.mappingWeightMlp = 1f;
}
}
}
@@ -1,15 +0,0 @@
fileFormatVersion: 2
guid: 367e952422ba44b82a0206d3b9cf12c4
labels:
- Ragdoll
- Falling
timeCreated: 1444739121
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 5f77f33a83efd35429c7eb5dc9474f43, type: 3}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,833 +0,0 @@
using UnityEngine;
using System.Collections;
using RootMotion;
namespace RootMotion.Dynamics {
/// <summary>
/// This behaviour handles pinning and unpinning puppets when they collide with objects or are hit via code, also automates getting up from an unbalanced state.
/// </summary>
[HelpURL("http://root-motion.com/puppetmasterdox/html/page10.html")]
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Behaviours/BehaviourPuppet")]
public partial class BehaviourPuppet : BehaviourBase {
// Open the User Manual URL
[ContextMenu("User Manual")]
void OpenUserManual() {
Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page10.html");
}
// Open the Script Reference URL
[ContextMenu("Scrpt Reference")]
void OpenScriptReference() {
Application.OpenURL("http://root-motion.com/puppetmasterdox/html/class_root_motion_1_1_dynamics_1_1_behaviour_puppet.html");
}
#region Main Properties
/// <summary>
/// Puppet means the character is in normal state and pinned. Unpinned means the character has lost balance and is animated physically in muscle space only. GetUp is a transition state from Unpinned to Puppet.
/// </summary>
[System.Serializable]
public enum State {
Puppet,
Unpinned,
GetUp
}
[System.Serializable]
public enum NormalMode {
Active,
Unmapped,
Kinematic
}
/// <summary>
/// Master properties for BehaviourPuppet. Options for switching modes and disabling mapping when the Puppet is out of contact.
/// </summary>
[System.Serializable]
public class MasterProps {
/// <summary>
/// How does the puppet behave when currently not in contact with anything? Active mode keeps the PuppetMaster Active and mapped at all times. Unmapped blends out mapping to maintain 100% animation quality. Kenamatic keeps the PuppetMaster in Kinematic mode until there is a collision.
/// </summary>
public NormalMode normalMode;
/// <summary>
/// "The speed of blending in mapping in case of contact when in Unmapped normal mode."
/// </summary>
public float mappingBlendSpeed = 10f;
/// <summary>
/// If false, static colliders will not activate the puppet when they collide with the muscles. Note that the static colliders need to have a kinematic Rigidbody attached for this to work. Used only in Kinematic normal mode.
/// </summary>
public bool activateOnStaticCollisions;
/// <summary>
/// Minimum collision impulse for activating the puppet. Used only in Kinematic normal mode.
/// </summary>
public float activateOnImpulse = 0f;
}
/// <summary>
/// Defines the properties of muscle behaviour.
/// </summary>
[System.Serializable]
public struct MuscleProps {
[TooltipAttribute("How much will collisions with muscles of this group unpin parent muscles?")]
/// <summary>
/// How much will collisions with muscles of this group unpin parent muscles?
/// </summary>
[Range(0f, 1f)] public float unpinParents;
[TooltipAttribute("How much will collisions with muscles of this group unpin child muscles?")]
/// <summary>
/// How much will collisions with muscles of this group unpin child muscles?
/// </summary>
[Range(0f, 1f)] public float unpinChildren;
[TooltipAttribute("How much will collisions with muscles of this group unpin muscles of the same group?")]
/// <summary>
/// How much will collisions with muscles of this group unpin muscles of the same group?
/// </summary>
[Range(0f, 1f)] public float unpinGroup;
[TooltipAttribute("If 1, muscles of this group will always be mapped to the ragdoll.")]
/// <summary>
/// If 1, muscles of this group will always be mapped to the ragdoll.
/// </summary>
[Range(0f, 1f)] public float minMappingWeight;
[TooltipAttribute("If 0, muscles of this group will not be mapped to the ragdoll pose even if they are unpinned.")]
/// <summary>
/// If 0, muscles of this group will not be mapped to the ragdoll pose even if they are unpinned.
/// </summary>
[Range(0f, 1f)] public float maxMappingWeight;
[TooltipAttribute("Defines minimum pin weight for the muscles. Muscle pin weight can’t be reduced beyond this value when damage occurs from collisions.")]
/// <summary>
/// Defines minimum pin weight for the muscles. Muscle pin weight can’t be reduced beyond this value when damage occurs from collisions.
/// </summary>
[Range(0f, 1f)] public float minPinWeight;
[TooltipAttribute("If true, muscles of this group will have their colliders disabled while in puppet state (not unbalanced nor getting up).")]
/// <summary>
/// If true, muscles of this group will have their colliders disabled while in puppet state (not unbalanced nor getting up).
/// </summary>
public bool disableColliders;
[TooltipAttribute("How fast will muscles of this group regain their pin weight (multiplier)?")]
/// <summary>
/// How fast will muscles of this group regain their pin weight (multiplier)?
/// </summary>
public float regainPinSpeed;
[TooltipAttribute("Smaller value means more unpinning from collisions (multiplier).")]
/// <summary>
/// Smaller value means more unpinning from collisions (multiplier).
/// </summary>
public float collisionResistance;
[TooltipAttribute("If the distance from the muscle to it's target is larger than this value, the character will be knocked out.")]
/// <summary>
/// If the distance from the muscle to it's target is larger than this value, the character will be knocked out.
/// </summary>
public float knockOutDistance;
[Tooltip("The PhysicsMaterial applied to the muscles while the character is in Puppet or GetUp state. Using a lower friction material reduces the risk of muscles getting stuck and pulled out of their joints.")]
/// <summary>
/// The PhysicsMaterial applied to the muscles while the character is in Puppet or GetUp state. Using a lower friction material reduces the risk of muscles getting stuck and pulled out of their joints.
/// </summary>
public PhysicMaterial puppetMaterial;
[Tooltip("The PhysicsMaterial applied to the muscles while the character is in Unpinned state.")]
/// <summary>
/// The PhysicsMaterial applied to the muscles while the character is in Unpinned state.
/// </summary>
public PhysicMaterial unpinnedMaterial;
}
/// <summary>
/// Defines the properties of muscle behaviour for certain muscle group(s).
/// </summary>
[System.Serializable]
public struct MusclePropsGroup {
// just for the Editor
[HideInInspector] public string name;
[TooltipAttribute("Muscle groups to which those properties apply.")]
/// <summary>
/// Muscle groups to which those properties apply.
/// </summary>
public Muscle.Group[] groups;
[TooltipAttribute("The muscle properties for those muscle groups.")]
/// <summary>
/// The muscle properties for those muscle groups.
/// </summary>
public MuscleProps props;
}
/// <summary>
/// Multiplies collision resistance for the specified layers.
/// </summary>
[System.Serializable]
public struct CollisionResistanceMultiplier {
public LayerMask layers;
[TooltipAttribute("Multiplier for the 'Collision Resistance' for these layers.")]
public float multiplier;
[TooltipAttribute("Overrides 'Collision Threshold' for these layers.")]
/// <summary>
/// Overrides 'Collision Threshold' for these layers.
/// </summary>
public float collisionThreshold;
}
[LargeHeader("Collision And Recovery")]
/// <summary>
/// Master properties for BehaviourPuppet. Options for switching modes and disabling mapping when the Puppet is out of contact.
/// </summary>
public MasterProps masterProps = new MasterProps();
[Tooltip("Will ground the target to those layers when getting up.")]
/// <summary>
/// Will ground the target to those layers when getting up.
/// </summary>
public LayerMask groundLayers;
[Tooltip("Will unpin the muscles that collide with those layers.")]
/// <summary>
/// Will unpin the muscles that collide with those layers.
/// </summary>
public LayerMask collisionLayers;
[Tooltip("The collision impulse sqrMagnitude threshold under which collisions will be ignored.")]
/// <summary>
/// The collision impulse sqrMagnitude threshold under which collisions will be ignored.
/// </summary>
public float collisionThreshold;
/// <summary>
/// Smaller value means more unpinning from collisions so the characters get knocked out more easily. If using a curve, the value will be evaluated by each muscle's target velocity magnitude. This can be used to make collision resistance higher while the character moves or animates faster.
/// </summary>
public Weight collisionResistance = new Weight(3f, "Smaller value means more unpinning from collisions so the characters get knocked out more easily. If using a curve, the value will be evaluated by each muscle's target velocity magnitude. This can be used to make collision resistance higher while the character moves or animates faster.");
[Tooltip("Multiplies collision resistance for the specified layers.")]
/// <summary>
/// Multiplies collision resistance for the specified layers.
/// </summary>
public CollisionResistanceMultiplier[] collisionResistanceMultipliers;
[Tooltip("An optimisation. Will only process up to this number of collisions per physics step.")]
/// <summary>
/// An optimisation. Will only process up to this number of collisions per physics step.
/// </summary>
[Range(1, 30)] public int maxCollisions = 30;
[Tooltip("How fast will the muscles of this group regain their pin weight?")]
/// <summary>
/// How fast will the muscles of this group regain their pin weight?
/// </summary>
[Range(0.001f, 10f)] public float regainPinSpeed = 1f;
[Tooltip("'Boosting' is a term used for making muscles temporarily immune to collisions and/or deal more damage to the muscles of other characters. That is done by increasing Muscle.State.immunity and Muscle.State.impulseMlp. For example when you set muscle.state.immunity to 1, boostFalloff will determine how fast this value will fall back to normal (0). Use BehaviourPuppet.BoostImmunity() and BehaviourPuppet.BoostImpulseMlp() for boosting from your own scripts. It is helpful for making the puppet stronger and deliever more punch while playing a melee hitting/kicking animation.")]
/// <summary>
/// 'Boosting' is a term used for making muscles temporarily immune to collisions and/or deal more damage to the muscles of other characters. That is done by increasing Muscle.State.immunity and Muscle.State.impulseMlp. For example when you set muscle.state.immunity to 1, boostFalloff will determine how fast this value will fall back to normal (0). Use BehaviourPuppet.BoostImmunity() and BehaviourPuppet.BoostImpulseMlp() for boosting from your own scripts. It is helpful for making the puppet stronger and deliever more punch while playing a melee hitting/kicking animation.
/// </summary>
public float boostFalloff = 1f;
[LargeHeader("Muscle Group Properties")]
[Tooltip("The default muscle properties. If there are no 'Group Overrides', this will be used for all muscles.")]
/// <summary>
/// The default muscle properties. If there are no 'Group Overrides', this will be used for all muscles.
/// </summary>
public MuscleProps defaults;
[Tooltip("Overriding default muscle properties for some muscle groups (for example making the feet stiffer or the hands looser).")]
/// <summary>
/// Overriding default muscle properties for some muscle groups (for example making the feet stiffer or the hands looser).
/// </summary>
public MusclePropsGroup[] groupOverrides;
[LargeHeader("Losing Balance")]
[Tooltip("If the distance from the muscle to it's target is larger than this value, the character will be knocked out.")]
/// <summary>
/// If the distance from the muscle to it's target is larger than this value, the character will be knocked out.
/// </summary>
[Range(0.001f, 10f)] public float knockOutDistance = 1f;
[Tooltip("Smaller value makes the muscles weaker when the puppet is knocked out.")]
/// <summary>
/// Smaller value makes the muscles weaker when the puppet is knocked out.
/// </summary>
[Range(0f, 1f)] public float unpinnedMuscleWeightMlp = 0.3f;
[Tooltip("Most character controllers apply supernatural accelerations to characters when changing running direction or jumping. It will require major pinning forces to be applied on the ragdoll to keep up with that acceleration. When a puppet collides with something at that point and is unpinned, those forces might shoot the puppet off to space. This variable limits the velocity of the ragdoll's Rigidbodies when the puppet is unpinned.")]
/// <summary>
/// Most character controllers apply supernatural accelerations to characters when changing running direction or jumping. It will require major pinning forces to be applied on the ragdoll to keep up with that acceleration. When a puppet collides with something at that point and is unpinned, those forces might shoot the puppet off to space. This variable limits the velocity of the ragdoll's Rigidbodies when the puppet is unpinned.
/// </summary>
public float maxRigidbodyVelocity = 10f;
[Tooltip("If a muscle has drifted farther than 'Knock Out Distance', will only unpin the puppet if it's pin weight is less than this value. Lowering this value will make puppets less likely to lose balance on minor collisions.")]
/// <summary>
/// If a muscle has drifted farther than 'Knock Out Distance', will only unpin the puppet if it's pin weight is less than this value. Lowering this value will make puppets less likely to lose balance on minor collisions.
/// </summary>
[Range(0f, 1f)] public float pinWeightThreshold = 1f;
[Tooltip("If false, will not unbalance the puppet by muscles that have their pin weight set to 0 in PuppetMaster muscle settings.")]
/// <summary>
/// If false, will not unbalance the puppet by muscles that have their pin weight set to 0 in PuppetMaster muscle settings.
/// </summary>
public bool unpinnedMuscleKnockout = true;
[Tooltip("If true, all muscles of the 'Prop' group will be detached from the puppet when it loses balance.")]
/// <summary>
/// If true, all muscles of the 'Prop' group will be detached from the puppet when it loses balance.
/// </summary>
public bool dropProps;
[LargeHeader("Getting Up")]
[Tooltip("If true, GetUp state will be triggerred automatically after 'Get Up Delay' and when the velocity of the hip muscle is less than 'Max Get Up Velocity'.")]
/// <summary>
/// If true, GetUp state will be triggerred automatically after 'Get Up Delay' and when the velocity of the hip muscle is less than 'Max Get Up Velocity'.
/// </summary>
public bool canGetUp = true;
[Tooltip("Minimum delay for getting up after loosing balance. After that time has passed, will wait for the velocity of the hip muscle to come down below 'Max Get Up Velocity' and then switch to the GetUp state.")]
/// <summary>
/// Minimum delay for getting up after loosing balance. After that time has passed, will wait for the velocity of the hip muscle to come down below 'Max Get Up Velocity' and then switch to the GetUp state.
/// </summary>
public float getUpDelay = 5f;
[Tooltip("The duration of blending the animation target from the ragdoll pose to the getting up animation once the GetUp state has been triggered.")]
/// <summary>
/// The duration of blending the animation target from the ragdoll pose to the getting up animation once the GetUp state has been triggered.
/// </summary>
public float blendToAnimationTime = 0.2f;
[Tooltip("Will not get up before the velocity of the hip muscle has come down to this value.")]
/// <summary>
/// Will not get up before the velocity of the hip muscle has come down to this value.
/// </summary>
public float maxGetUpVelocity = 0.3f;
[Tooltip("The duration of the 'GetUp' state after which it switches to the 'Puppetä state.")]
/// <summary>
/// The duration of the "GetUp" state after which it switches to the "Puppet" state.
/// </summary>
public float minGetUpDuration = 1f;
[Tooltip("Collision resistance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.")]
/// <summary>
/// Collision resistance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
/// </summary>
public float getUpCollisionResistanceMlp = 2f;
[Tooltip("Regain pin weight speed multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.")]
/// <summary>
/// Regain pin weight speed multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
/// </summary>
public float getUpRegainPinSpeedMlp = 2f;
[Tooltip("Knock out distance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.")]
/// <summary>
/// Knock out distance multiplier while in the GetUp state. Increasing this will prevent the character from loosing balance again immediatelly after going from Unpinned to GetUp state.
/// </summary>
public float getUpKnockOutDistanceMlp = 10f;
[Tooltip("Offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a prone pose. Tweak this value if your character slides a bit when starting to get up.")]
/// <summary>
/// Offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a prone pose. Tweak this value if your character slides a bit when starting to get up.
/// </summary>
public Vector3 getUpOffsetProne;
[Tooltip("Offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a supine pose. Tweak this value if your character slides a bit when starting to get up.")]
/// <summary>
/// Offset of the target character (in character rotation space) from the hip bone when initiating getting up animation from a supine pose. Tweak this value if your character slides a bit when starting to get up.
/// </summary>
public Vector3 getUpOffsetSupine;
[LargeHeader("Events")]
[Tooltip("Called when the character starts getting up from a prone pose (facing down).")]
/// <summary>
/// Called when the character starts getting up from a prone pose (facing down).
/// </summary>
public PuppetEvent onGetUpProne;
[Tooltip("Called when the character starts getting up from a supine pose (facing up).")]
/// <summary>
/// Called when the character starts getting up from a supine pose (facing up).
/// </summary>
public PuppetEvent onGetUpSupine;
[Tooltip("Called when the character is knocked out (loses balance). Doesn't matter from which state.")]
/// <summary>
/// Called when the character is knocked out (loses balance). Doesn't matter from which state.
/// </summary>
public PuppetEvent onLoseBalance;
[Tooltip("Called when the character is knocked out (loses balance) only from the normal Puppet state.")]
/// <summary>
/// Called when the character is knocked out (loses balance) only from the normal Puppet state.
/// </summary>
public PuppetEvent onLoseBalanceFromPuppet;
[Tooltip("Called when the character is knocked out (loses balance) only from the GetUp state.")]
/// <summary>
/// Called when the character is knocked out (loses balance) only from the GetUp state.
/// </summary>
public PuppetEvent onLoseBalanceFromGetUp;
[Tooltip("Called when the character has fully recovered and switched to the Puppet state.")]
/// <summary>
/// Called when the character has fully recovered and switched to the Puppet state.
/// </summary>
public PuppetEvent onRegainBalance;
public delegate void CollisionImpulseDelegate(MuscleCollision m, float impulse);
/// <summary>
/// Called when any of the puppet's muscles has had a collision.
/// </summary>
public CollisionDelegate OnCollision;
/// <summary>
/// Called when any of the puppet's muscles has had a collision and that collision has resulted in a loss of pinning.
/// </summary>
public CollisionImpulseDelegate OnCollisionImpulse;
/// <summary>
/// Gets the current state of the puppet (Puppet/Unpinned/GetUp).
/// </summary>
public State state { get; private set; }
/// <summary>
/// If false, BehaviourPuppet will not move the target root while unpinned or getting up. Useful if target root is synced over the network.
/// </summary>
[HideInInspector] public bool canMoveTarget = true;
// Called when the PuppetMaster has been deactivated (by parenting it to an inactive hierarchy or calling SetActive(false)).
public override void OnReactivate() {
state = puppetMaster.state == PuppetMaster.State.Alive? State.Puppet: State.Unpinned;
getUpTimer = 0f;
unpinnedTimer = 0f;
getupAnimationBlendWeight = 0f;
getupAnimationBlendWeightV = 0f;
getUpTargetFixed = false;
getupDisabled = puppetMaster.state != RootMotion.Dynamics.PuppetMaster.State.Alive;
state = puppetMaster.state == RootMotion.Dynamics.PuppetMaster.State.Alive? State.Puppet: State.Unpinned;
foreach (Muscle m in puppetMaster.muscles) {
// Pin, muscle weight and damper already set in PuppetMaster
if (!m.state.isDisconnected) SetColliders(m, state == State.Unpinned);
}
//Activate();
enabled = true;
}
/// <summary>
/// Resets this puppet to the specified position and rotation and normal Puppet state. Use this for respawning existing puppets.
/// </summary>
public void Reset(Vector3 position, Quaternion rotation) {
Debug.LogWarning("BehaviourPuppet.Reset has been deprecated, please use PuppetMaster.Teleport instead.");
}
public override void OnTeleport(Quaternion deltaRotation, Vector3 deltaPosition, Vector3 pivot, bool moveToTarget) {
getUpPosition = pivot + deltaRotation * (getUpPosition - pivot) + deltaPosition;
if (moveToTarget) {
getupAnimationBlendWeight = 0f;
getupAnimationBlendWeightV = 0f;
}
}
#endregion Main Properties
private float unpinnedTimer;
private float getUpTimer;
private Vector3 hipsForward;
private Vector3 hipsUp;
private float getupAnimationBlendWeight, getupAnimationBlendWeightV;
private bool getUpTargetFixed;
private NormalMode lastNormalMode;
private int collisions;
private bool eventsEnabled;
private float lastKnockOutDistance;
private float knockOutDistanceSqr;
private bool getupDisabled;
private bool hasCollidedSinceGetUp;
protected override void OnInitiate() {
foreach (CollisionResistanceMultiplier crm in collisionResistanceMultipliers) {
if (crm.layers == 0) {
Debug.LogWarning("BehaviourPuppet has a Collision Resistance Multiplier that's layers is set to Nothing. Please add some layers.", transform);
}
}
/* // What if the puppet needs to be grounded to a collisin object during getting up?
int[] groundLayerIndexes = LayerMaskExtensions.MaskToNumbers(groundLayers);
for (int i = 0; i < groundLayerIndexes.Length; i++) {
if (LayerMaskExtensions.Contains(collisionLayers, groundLayerIndexes[i])) {
Debug.LogWarning("BehaviourPuppet 'Collision Layers' contains one of the layers in the 'Ground Layers'. This will make the Puppet lose balance when the feet collide with the ground.");
}
}
*/
foreach (Muscle m in puppetMaster.muscles) {
if (m.joint.gameObject.layer == puppetMaster.targetRoot.gameObject.layer) {
Debug.LogWarning("One of the ragdoll bones is on the same layer as the animated character. This might make the ragdoll collide with the character controller.");
}
if (!Physics.GetIgnoreLayerCollision(m.joint.gameObject.layer, puppetMaster.targetRoot.gameObject.layer)) {
Debug.LogWarning("The ragdoll layer (" + m.joint.gameObject.layer + ") and the character controller layer (" + puppetMaster.targetRoot.gameObject.layer + ") are not set to ignore each other in Edit/Project Settings/Physics/Layer Collision Matrix. This might cause the ragdoll bones to collide with the character controller.");
}
}
hipsForward = Quaternion.Inverse(puppetMaster.muscles[0].transform.rotation) * puppetMaster.targetRoot.forward;
hipsUp = Quaternion.Inverse(puppetMaster.muscles[0].transform.rotation) * puppetMaster.targetRoot.up;
state = State.Unpinned;
eventsEnabled = true;
}
protected override void OnActivate() {
// Start with unpinned on puppet state
bool unpinned = true;
if (puppetMaster.pinWeight >= 1f)
{
foreach (Muscle m in puppetMaster.muscles)
{
if (m.state.pinWeightMlp > 0.5f)
{
unpinned = false;
break;
}
}
}
bool e = eventsEnabled;
eventsEnabled = false;
if (unpinned) SetState(State.Unpinned);
else SetState(State.Puppet);
eventsEnabled = e;
}
public override void KillStart() {
getupDisabled = true;
foreach (Muscle m in puppetMaster.muscles) {
if (!m.state.isDisconnected)
{
m.state.pinWeightMlp = 0f;
if (hasBoosted) m.state.immunity = 0f;
// Change physic materials
SetColliders(m, true);
}
}
}
public override void KillEnd() {
SetState(State.Unpinned);
}
public override void Resurrect() {
getupDisabled = false;
if (state == State.Unpinned) {
getUpTimer = Mathf.Infinity;
unpinnedTimer = Mathf.Infinity;
getupAnimationBlendWeight = 0f;
getupAnimationBlendWeightV = 0f;
foreach (Muscle m in puppetMaster.muscles) {
m.state.pinWeightMlp = 0f;
}
}
}
protected override void OnDeactivate() {
state = State.Unpinned;
}
protected override void OnFixedUpdate() {
collisions = 0;
if (dropPropFlag) {
RemovePropMuscles();
foreach (PropMuscle m in puppetMaster.propMuscles)
{
m.currentProp = null;
}
dropPropFlag = false;
}
// If the PuppetMaster is not active, make sure the puppet is in the Puppet state and return.
if (!puppetMaster.isActive && !puppetMaster.isSwitchingMode)
{
SetState(State.Puppet);
return;
}
if (!puppetMaster.isAlive) {
foreach (Muscle m in puppetMaster.muscles) {
if (!m.state.isDisconnected)
{
m.state.pinWeightMlp = 0f;
m.state.mappingWeightMlp = Mathf.MoveTowards(m.state.mappingWeightMlp, 1f, Time.deltaTime * 5f);
}
}
return;
}
// Boosting falloff
if (hasBoosted) {
foreach (Muscle m in puppetMaster.muscles) {
if (!m.state.isDisconnected)
{
m.state.immunity = Mathf.MoveTowards(m.state.immunity, 0f, Time.deltaTime * boostFalloff);
m.state.impulseMlp = Mathf.Lerp(m.state.impulseMlp, 1f, Time.deltaTime * boostFalloff);
}
}
}
// Getting up and making sure the puppet stays unpinned and mapped
if (state == State.Unpinned) {
unpinnedTimer += Time.deltaTime;
if (unpinnedTimer >= getUpDelay && canGetUp && !getupDisabled && puppetMaster.muscles[0].rigidbody.velocity.magnitude < maxGetUpVelocity) {
SetState(State.GetUp);
return;
}
foreach (Muscle m in puppetMaster.muscles) {
if (!m.state.isDisconnected)
{
m.state.pinWeightMlp = 0f;
m.state.mappingWeightMlp = Mathf.MoveTowards(m.state.mappingWeightMlp, 1f, Time.deltaTime * masterProps.mappingBlendSpeed);
}
}
}
// In PUPPET and GETUP states...
if (state != State.Unpinned && !puppetMaster.isKilling) {
if (knockOutDistance != lastKnockOutDistance) {
knockOutDistanceSqr = Mathf.Sqrt(knockOutDistance);
lastKnockOutDistance = knockOutDistance;
}
foreach (Muscle m in puppetMaster.muscles) {
var props = GetProps(m.props.group);
float stateMlp = 1f;
if (state == State.GetUp) {// && getUpTimer < 0.5f) {
stateMlp = Mathf.Lerp(getUpKnockOutDistanceMlp, stateMlp, m.state.pinWeightMlp);
}
float offset = unpinnedMuscleKnockout? m.positionOffset.sqrMagnitude: m.positionOffset.sqrMagnitude * m.props.pinWeight * puppetMaster.pinWeight;
if (puppetMaster.pinWeight < 1f) hasCollidedSinceGetUp = true;
float pinW = m.state.pinWeightMlp * m.props.pinWeight * puppetMaster.pinWeight;
// [PuppetMaster 0.5 and earlier] if (!puppetMaster.isBlending && m.state.pinWeightMlp < 0.5f && m.positionOffset.sqrMagnitude * m.props.pinWeight > props.knockOutDistance * knockOutDistanceSqr * stateMlp) {
// [PuppetMaster 0.6] if (hasCollidedSinceGetUp && !puppetMaster.isBlending && m.state.pinWeightMlp < 1f && m.positionOffset.sqrMagnitude > props.knockOutDistance * knockOutDistanceSqr * stateMlp) {
if (hasCollidedSinceGetUp && !m.state.isDisconnected && !puppetMaster.isBlending && offset > 0f && pinW <= pinWeightThreshold && offset > props.knockOutDistance * knockOutDistanceSqr * stateMlp) {
if (state != State.GetUp || getUpTargetFixed) {
SetState(State.Unpinned);
}
return;
}
if (!m.state.isDisconnected)
{
m.state.muscleWeightMlp = Mathf.Lerp(unpinnedMuscleWeightMlp, 1f, m.state.pinWeightMlp);
if (state == State.GetUp) m.state.muscleDamperAdd = 0f;
if (!puppetMaster.isKilling)
{
float speedF = 1f;
if (state == State.GetUp) speedF = Mathf.Lerp(getUpRegainPinSpeedMlp, 1f, m.state.pinWeightMlp);
m.state.pinWeightMlp += Time.deltaTime * props.regainPinSpeed * regainPinSpeed * speedF;
}
}
}
// Max pin weight from the legs and feet
float maxPinWeight = 1f;
foreach (Muscle m in puppetMaster.muscles) {
if (m.props.group == Muscle.Group.Leg || m.props.group == Muscle.Group.Foot) {
if (!m.state.isDisconnected && m.state.pinWeightMlp < maxPinWeight) maxPinWeight = m.state.pinWeightMlp;
}
}
foreach (Muscle m in puppetMaster.muscles) {
m.state.pinWeightMlp = Mathf.Clamp(m.state.pinWeightMlp, 0, maxPinWeight * 5f);
}
}
// Ending GetUp
if (state == State.GetUp) {
getUpTimer += Time.deltaTime;
if (getUpTimer > minGetUpDuration) {
getUpTimer = 0f;
SetState(State.Puppet);
}
}
}
protected override void OnLateUpdate() {
// Used in PuppetMasterModes
forceActive = state != State.Puppet;
if (!puppetMaster.isAlive) return;
// Normal mode switching
if (masterProps.normalMode != lastNormalMode) {
if (lastNormalMode == NormalMode.Unmapped) {
foreach (Muscle m in puppetMaster.muscles) m.state.mappingWeightMlp = 1f;
}
if (lastNormalMode == NormalMode.Kinematic) {
if (puppetMaster.mode == PuppetMaster.Mode.Kinematic) puppetMaster.mode = PuppetMaster.Mode.Active;
}
lastNormalMode = masterProps.normalMode;
}
// Normal modes
switch(masterProps.normalMode) {
case NormalMode.Unmapped:
if (puppetMaster.isActive) {
bool to = puppetMaster.pinWeight < 1f;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
BlendMuscleMapping(i, ref to);
}
}
break;
case NormalMode.Kinematic:
if (SetKinematic()) {
puppetMaster.mode = PuppetMaster.Mode.Kinematic;
}
break;
default:break;
}
}
private bool SetKinematic() {
if (!puppetMaster.isActive) return false;
if (state != State.Puppet) return false;
if (puppetMaster.isBlending) return false;
if (getupAnimationBlendWeight > 0f) return false;
if (!puppetMaster.isAlive) return false;
foreach (Muscle m in puppetMaster.muscles) {
if (!m.state.isDisconnected && m.state.pinWeightMlp < 1f) return false;
}
return true;
}
// Called when the PuppetMaster reads
protected override void OnReadBehaviour() {
if (!enabled) return;
if (!puppetMaster.isFrozen) {
if (state == State.Unpinned && puppetMaster.isActive && !puppetMaster.isBlending && !puppetMaster.muscles[0].state.isDisconnected) {
//if (state == State.Unpinned && puppetMaster.isActive && !puppetMaster.muscles[0].state.isDisconnected) {
MoveTarget(puppetMaster.muscles[0].rigidbody.position);
GroundTarget(groundLayers);
getUpPosition = puppetMaster.targetRoot.position;
}
}
// Prevents root motion from snapping the target to another position
if (state == State.GetUp && getUpTimer < minGetUpDuration * 0.1f)
{
Vector3 y = Vector3.Project(puppetMaster.targetRoot.position - getUpPosition, puppetMaster.targetRoot.up);
getUpPosition += y;
MoveTarget(getUpPosition);
}
if (getupAnimationBlendWeight > 0f) {
Vector3 y = Vector3.Project(puppetMaster.targetRoot.position - getUpPosition, puppetMaster.targetRoot.up);
getUpPosition += y;
MoveTarget(getUpPosition);
getupAnimationBlendWeight = Mathf.SmoothDamp(getupAnimationBlendWeight, 0f, ref getupAnimationBlendWeightV, blendToAnimationTime);
if (getupAnimationBlendWeight < 0.01f) getupAnimationBlendWeight = 0f;
// Lerps the target pose to last sampled mapped pose. Starting off from the ragdoll pose
puppetMaster.FixTargetToSampledState(getupAnimationBlendWeight);
}
getUpTargetFixed = true;
}
private void BlendMuscleMapping(int muscleIndex, ref bool to) {
if (puppetMaster.muscles[muscleIndex].state.pinWeightMlp < 1) to = true;
var props = GetProps(puppetMaster.muscles[muscleIndex].props.group);
float target = to? (state == State.Puppet? props.maxMappingWeight: 1f): props.minMappingWeight;
puppetMaster.muscles[muscleIndex].state.mappingWeightMlp = Mathf.MoveTowards(puppetMaster.muscles[muscleIndex].state.mappingWeightMlp, target, Time.deltaTime * masterProps.mappingBlendSpeed);
}
public override void OnMuscleAdded(Muscle m) {
base.OnMuscleAdded(m);
SetColliders(m, state == State.Unpinned);
}
public override void OnMuscleRemoved(Muscle m) {
base.OnMuscleRemoved(m);
SetColliders(m, true);
}
protected void MoveTarget(Vector3 position) {
if (!canMoveTarget) return;
puppetMaster.targetRoot.position = position;
}
protected void RotateTarget(Quaternion rotation) {
if (!canMoveTarget) return;
puppetMaster.targetRoot.rotation = rotation;
}
protected override void GroundTarget(LayerMask layers) {
if (canMoveTarget) base.GroundTarget (layers);
}
void OnDrawGizmosSelected() {
for (int g = 0; g < groupOverrides.Length; g++) {
groupOverrides[g].name = string.Empty;
if (groupOverrides[g].groups.Length > 0) {
for (int i = 0; i < groupOverrides[g].groups.Length; i++) {
if (i > 0) groupOverrides[g].name += ", ";
groupOverrides[g].name += groupOverrides[g].groups[i].ToString();
}
}
}
}
}
}
@@ -1,15 +0,0 @@
fileFormatVersion: 2
guid: 1efacf79ab4214e85aeebfd07064c20f
labels:
- Active
- Activeragdolls
timeCreated: 1444739105
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 1b10303a9012d794dbcd05b1f7f818bb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,118 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
// Handles the boosting functionality of BehaviourPuppet
public partial class BehaviourPuppet : BehaviourBase {
private bool hasBoosted;
/// <summary>
/// Boosts both immunity and impulseMlp for the entire puppet.
/// </summary>
public void Boost(float immunity, float impulseMlp) {
hasBoosted = true;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
Boost(i, immunity, impulseMlp);
}
}
/// <summary>
/// Boosts both immunity and impulseMlp for the specified muscle.
/// </summary>
public void Boost(int muscleIndex, float immunity, float impulseMlp) {
hasBoosted = true;
BoostImmunity(muscleIndex, immunity);
BoostImpulseMlp(muscleIndex, impulseMlp);
}
/// <summary>
/// Boosts both immunity and impulseMlp for the specified muscle and other muscles according to the boostParents and boostChildren falloffs.
/// </summary>
public void Boost(int muscleIndex, float immunity, float impulseMlp, float boostParents, float boostChildren) {
hasBoosted = true;
if (boostParents <= 0f && boostChildren <= 0f) {
Boost (muscleIndex, immunity, impulseMlp);
return;
}
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
float falloff = GetFalloff(i, muscleIndex, boostParents, boostChildren);
Boost(i, immunity * falloff, impulseMlp * falloff);
}
}
/// <summary>
/// Sets the immunity of all the muscles to the specified value. Immunity reduces damage from collisions and hits. Immunity will be lerped back to normal automatically (boostFalloff).
/// </summary>
public void BoostImmunity(float immunity) {
hasBoosted = true;
if (immunity < 0f) return;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
BoostImmunity(i, immunity);
}
}
/// <summary>
/// Sets the immunity of the muscle at the muscleIndex to the specified value. Immunity reduces damage from collisions and hits. Immunity will be lerped back to normal automatically (boostFalloff).
/// </summary>
public void BoostImmunity(int muscleIndex, float immunity) {
hasBoosted = true;
puppetMaster.muscles[muscleIndex].state.immunity = Mathf.Clamp(immunity, puppetMaster.muscles[muscleIndex].state.immunity, 1f);
}
/// <summary>
/// Sets the immunity of the muscle at the muscleIndex (and other muscles according to boostParents and boostChildren falloffs) to the specified value. Immunity reduces damage from collisions and hits. Immunity will be lerped back to normal automatically (boostFalloff).
/// </summary>
public void BoostImmunity(int muscleIndex, float immunity, float boostParents, float boostChildren) {
hasBoosted = true;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
float falloff = GetFalloff(i, muscleIndex, boostParents, boostChildren);
BoostImmunity(i, immunity * falloff);
}
}
/// <summary>
/// Sets the impulse multiplier of all the muscles to the specified value. Larger impulse multiplier makes the muscles deal more damage to the muscles of other characters. Muscle impulse multipliers will be lerped back to normal automaticalle (boostFalloff).
/// </summary>
public void BoostImpulseMlp(float impulseMlp) {
hasBoosted = true;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
BoostImpulseMlp(i, impulseMlp);
}
}
/// <summary>
/// Sets the impulse multiplier of the muscle at the muscleIndex to the specified value. Larger impulse multiplier makes the muscle deal more damage to the muscles of other characters. Muscle impulse multipliers will be lerped back to normal automaticalle (boostFalloff).
/// </summary>
public void BoostImpulseMlp(int muscleIndex, float impulseMlp) {
hasBoosted = true;
puppetMaster.muscles[muscleIndex].state.impulseMlp = Mathf.Max(impulseMlp, puppetMaster.muscles[muscleIndex].state.impulseMlp);
}
/// <summary>
/// Sets the impulse multiplier of the muscle at the muscleIndex (and other muscles according to boostParents and boostChildren falloffs) to the specified value. Larger impulse multiplier makes the muscle deal more damage to the muscles of other characters. Muscle impulse multipliers will be lerped back to normal automaticalle (boostFalloff).
/// </summary>
public void BoostImpulseMlp(int muscleIndex, float impulseMlp, float boostParents, float boostChildren) {
hasBoosted = true;
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
float falloff = GetFalloff(i, muscleIndex, boostParents, boostChildren);
BoostImpulseMlp(i, impulseMlp * falloff);
}
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: dfbba8c5a98ca4de682ccf628687b20c
timeCreated: 1438863362
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,157 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
// Handles damaging the puppet via collisions and hits.
public partial class BehaviourPuppet : BehaviourBase {
private MuscleCollisionBroadcaster broadcaster;
/// <summary>
/// Knock out this puppet.
/// </summary>
public void Unpin() {
Debug.Log("BehaviourPuppet.Unpin() has been deprecated. Use SetState(BehaviourPuppet.State) instead.");
SetState(State.Unpinned);
}
// When a muscle is hit (through MuscleCollisionBroadcaster.Hit(...))
protected override void OnMuscleHitBehaviour(MuscleHit hit) {
// Should we activate the puppet?
if (masterProps.normalMode == NormalMode.Kinematic) puppetMaster.mode = PuppetMaster.Mode.Active;
// Unpin the muscle (and other muscles) and add force
UnPin(hit.muscleIndex, hit.unPin);
// Add force
puppetMaster.muscles[hit.muscleIndex].SetKinematic(false);
puppetMaster.muscles[hit.muscleIndex].rigidbody.AddForceAtPosition(hit.force, hit.position);
}
// When a muscle collides with something (called by the MuscleCollisionBroadcaster component on the muscle).
protected override void OnMuscleCollisionBehaviour(MuscleCollision m) {
if (OnCollision != null) OnCollision(m);
// All the conditions for ignoring this
if (!enabled) return;
if (state == State.Unpinned) return;
if (collisions > maxCollisions) return;
if (!LayerMaskExtensions.Contains(collisionLayers, m.collision.gameObject.layer)) return;
if (LayerMaskExtensions.Contains(groundLayers, m.collision.gameObject.layer)) {
if (state == State.GetUp) return; // Do not damage if contact with ground layers and in getup state
if (puppetMaster.muscles[m.muscleIndex].props.group == Muscle.Group.Foot) return; // Do not damage if feet in contact with ground layers
}
if (masterProps.normalMode == NormalMode.Kinematic && !puppetMaster.isActive && !masterProps.activateOnStaticCollisions && m.collision.gameObject.isStatic) return;
// Get the collision impulse on the muscle
float cT = collisionThreshold;
float impulse = GetImpulse(m, ref cT);
float minImpulseMlp = PuppetMasterSettings.instance != null? (1f + PuppetMasterSettings.instance.currentlyActivePuppets * PuppetMasterSettings.instance.activePuppetCollisionThresholdMlp): 1f;
float minImpulse = cT * minImpulseMlp;
if (impulse <= minImpulse) return;
collisions ++;
// Try to find out if it collided with another puppet's muscle
if (m.collision.collider.attachedRigidbody != null) {
broadcaster = m.collision.collider.attachedRigidbody.GetComponent<MuscleCollisionBroadcaster>();
if (broadcaster != null) {
if (broadcaster.muscleIndex < broadcaster.puppetMaster.muscles.Length) {
// Multiply impulse (if the other muscle has been boosted)
impulse *= broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].state.impulseMlp;
//float stayF = m.isStay? 0.05f: 0.1f;
//broadcaster.puppetMaster.muscles[broadcaster.muscleIndex].offset -= m.collision.impulse * Time.deltaTime * stayF;
}
}
}
// DO not move this up, the impulse value will be wrong.
// Let other scripts know about the collision (even the ones below collision threshold)
if (OnCollisionImpulse != null) OnCollisionImpulse(m, impulse);
// Should we activate the puppet?
if (Activate(m.collision, impulse)) puppetMaster.mode = PuppetMaster.Mode.Active;
// Unpin the muscle (and other muscles)
UnPin(m.muscleIndex, impulse);
}
// Calculating the impulse magnitude from a collision
private float GetImpulse(MuscleCollision m, ref float layerThreshold) {
float i = m.collision.impulse.sqrMagnitude;
i /= puppetMaster.muscles [m.muscleIndex].rigidbody.mass;
i *= 0.3f; // Coeficient for evening out for pre-0.3 versions
// Collision resistance multipliers
foreach (CollisionResistanceMultiplier crm in collisionResistanceMultipliers) {
if (LayerMaskExtensions.Contains(crm.layers, m.collision.collider.gameObject.layer)) {
if (crm.multiplier <= 0f) i = Mathf.Infinity;
else i /= crm.multiplier;
layerThreshold = crm.collisionThreshold;
break;
}
}
return i;
}
// Unpin a muscle and other muscles linked to it
private void UnPin(int muscleIndex, float unpin) {
if (muscleIndex >= puppetMaster.muscles.Length) return;
BehaviourPuppet.MuscleProps props = GetProps(puppetMaster.muscles[muscleIndex].props.group);
for (int i = 0; i < puppetMaster.muscles.Length; i++) {
UnPinMuscle(i, unpin * GetFalloff(i, muscleIndex, props.unpinParents, props.unpinChildren, props.unpinGroup));
}
hasCollidedSinceGetUp = true;
}
// Unpin a specific muscle according to it's collision resistance, immunity and other values
private void UnPinMuscle(int muscleIndex, float unpin) {
// All the conditions to ignore this
if (unpin <= 0f) return;
if (puppetMaster.muscles[muscleIndex].state.immunity >= 1f) return;
// Find the group properties
BehaviourPuppet.MuscleProps props = GetProps(puppetMaster.muscles[muscleIndex].props.group);
// Making the puppet more resistant to collisions while getting up
float stateF = 1f;
if (state == State.GetUp) stateF = Mathf.Lerp(getUpCollisionResistanceMlp, 1f, puppetMaster.muscles[muscleIndex].state.pinWeightMlp);
// Applying collision resistance
float cR = collisionResistance.mode == Weight.Mode.Float? collisionResistance.floatValue: collisionResistance.GetValue(puppetMaster.muscles[muscleIndex].targetVelocity.magnitude);
float damage = unpin / (props.collisionResistance * cR * stateF);
damage *= 1f - puppetMaster.muscles[muscleIndex].state.immunity;
// Finally apply the damage
//puppetMaster.muscles[muscleIndex].state.pinWeightMlp -= damage;
if (!puppetMaster.muscles[muscleIndex].state.isDisconnected)
{
puppetMaster.muscles[muscleIndex].state.pinWeightMlp = Mathf.Max(puppetMaster.muscles[muscleIndex].state.pinWeightMlp - damage, props.minPinWeight);
}
}
private bool Activate(Collision collision, float impulse) {
if (masterProps.normalMode != NormalMode.Kinematic) return false;
if (puppetMaster.mode != PuppetMaster.Mode.Kinematic) return false;
if (impulse < masterProps.activateOnImpulse) return false;
if (collision.gameObject.isStatic) {
return masterProps.activateOnStaticCollisions;
}
return true;
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: c8748f43422c345aa87a97dd3e85819e
timeCreated: 1438864141
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,65 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
// Helper methods for BehaviourPuppet
public partial class BehaviourPuppet : BehaviourBase {
/// <summary>
/// Determines whether this ragdoll is facing up (false) or down (true).
/// </summary>
public bool IsProne() {
float dot = Vector3.Dot(puppetMaster.muscles[0].transform.rotation * hipsForward, puppetMaster.targetRoot.up);
return dot < 0f;
}
// Gets the falloff value of muscle 'i' according to it's kinship degree from muscle 'muscleIndex' and the parent and child falloff values.
private float GetFalloff(int i, int muscleIndex, float falloffParents, float falloffChildren) {
if (i == muscleIndex) return 1f;
bool isChild = puppetMaster.muscles[muscleIndex].childFlags[i];
int kinshipDegree = puppetMaster.muscles[muscleIndex].kinshipDegrees[i];
return Mathf.Pow(isChild? falloffChildren: falloffParents, kinshipDegree);
}
// Gets the falloff value of muscle 'i' according to it's kinship degree from muscle 'muscleIndex' and the parent, child and group falloff values.
private float GetFalloff(int i, int muscleIndex, float falloffParents, float falloffChildren, float falloffGroup) {
float falloff = GetFalloff(i, muscleIndex, falloffParents, falloffChildren);
if (falloffGroup > 0f && i != muscleIndex && InGroup(puppetMaster.muscles[i].props.group, puppetMaster.muscles[muscleIndex].props.group)) {
falloff = Mathf.Max(falloff, falloffGroup);
}
return falloff;
}
// Returns true is the groups match directly OR in the group overrides.
private bool InGroup(Muscle.Group group1, Muscle.Group group2) {
if (group1 == group2) return true;
foreach (MusclePropsGroup musclePropsGroup in groupOverrides) {
foreach (Muscle.Group g in musclePropsGroup.groups) {
if (g == group1) {
foreach (Muscle.Group g2 in musclePropsGroup.groups) {
if (g2 == group2) return true;
}
}
}
}
return false;
}
// Returns the MusclePropsGroup of the specified muscle group.
private MuscleProps GetProps(Muscle.Group group) {
foreach (MusclePropsGroup g in groupOverrides) {
foreach (Muscle.Group group2 in g.groups) {
if (group2 == group) return g.props;
}
}
return defaults;
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7d5fdd3d0ce82440097da4ed39d5dc5d
timeCreated: 1438863597
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,258 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics
{
// Handles switching BehaviourPuppet states.
public partial class BehaviourPuppet : BehaviourBase
{
private Vector3 getUpPosition;
private bool dropPropFlag;
// Force the puppet to another state
public void SetState(State newState)
{
// If already in this state, do nothing
if (state == newState) return;
switch (newState)
{
// Switching to the PUPPET state
case State.Puppet:
puppetMaster.SampleTargetMappedState();
unpinnedTimer = 0f;
getUpTimer = 0f;
hasCollidedSinceGetUp = false;
//getupAnimationBlendWeight = 0f;
//getupAnimationBlendWeightV = 0f;
// If switching from the unpinned state...
if (state == State.Unpinned)
{
// Repin the puppet
foreach (Muscle m in puppetMaster.muscles)
{
if (!m.state.isDisconnected)
{
m.state.pinWeightMlp = 1f;
m.state.muscleWeightMlp = 1f;
m.state.muscleDamperAdd = 0f;
m.positionOffset = Vector3.zero;
// Change physyc materials
SetColliders(m, false);
}
}
}
// Call events
state = State.Puppet;
if (eventsEnabled)
{
onRegainBalance.Trigger(puppetMaster);
if (onRegainBalance.switchBehaviour) return;
}
break;
// Switching to the UNPINNED state
case State.Unpinned:
unpinnedTimer = 0f;
getUpTimer = 0f;
getupAnimationBlendWeight = 0f;
getupAnimationBlendWeightV = 0f;
foreach (Muscle m in puppetMaster.muscles)
{
if (hasBoosted) m.state.immunity = 0f;
if (maxRigidbodyVelocity != Mathf.Infinity)
{
m.rigidbody.velocity = Vector3.ClampMagnitude(m.rigidbody.velocity, maxRigidbodyVelocity);
m.mappedVelocity = Vector3.ClampMagnitude(m.mappedVelocity, maxRigidbodyVelocity);
}
// Change physic materials
SetColliders(m, true);
}
// Drop all the props
if (dropProps)
{
dropPropFlag = true;
}
foreach (Muscle m in puppetMaster.muscles)
{
if (!m.state.isDisconnected)
{
m.state.muscleWeightMlp = puppetMaster.isAlive ? unpinnedMuscleWeightMlp : puppetMaster.stateSettings.deadMuscleWeight;
}
}
// Trigger events
onLoseBalance.Trigger(puppetMaster, puppetMaster.isAlive);
if (onLoseBalance.switchBehaviour)
{
state = State.Unpinned;
return;
}
// Trigger some more events
if (state == State.Puppet)
{
onLoseBalanceFromPuppet.Trigger(puppetMaster, puppetMaster.isAlive);
if (onLoseBalanceFromPuppet.switchBehaviour)
{
state = State.Unpinned;
return;
}
}
else
{
onLoseBalanceFromGetUp.Trigger(puppetMaster, puppetMaster.isAlive);
if (onLoseBalanceFromGetUp.switchBehaviour)
{
state = State.Unpinned;
return;
}
}
// Unpin the muscles. This is done after the events in case behaviours are switched and the next behaviour might need the weights as they were
foreach (Muscle m in puppetMaster.muscles)
{
m.state.pinWeightMlp = 0f;
}
break;
// Switching to the GETUP state
case State.GetUp:
unpinnedTimer = 0f;
getUpTimer = 0f;
hasCollidedSinceGetUp = false;
// Is the ragdoll facing up or down?
bool isProne = IsProne();
state = State.GetUp;
// Trigger events
if (isProne)
{
onGetUpProne.Trigger(puppetMaster);
if (onGetUpProne.switchBehaviour) return;
}
else
{
onGetUpSupine.Trigger(puppetMaster);
if (onGetUpSupine.switchBehaviour) return;
}
// Unpin the puppet just in case
foreach (Muscle m in puppetMaster.muscles)
{
if (!m.state.isDisconnected)
{
/*
m.state.muscleWeightMlp = 0f;
m.state.pinWeightMlp = 0f;
m.state.muscleDamperAdd = 0f;
*/
// Change physic materials
SetColliders(m, false);
}
}
// Set the target's rotation
Vector3 spineDirection = puppetMaster.muscles[0].rigidbody.rotation * hipsUp;
Vector3 normal = puppetMaster.targetRoot.up;
Vector3.OrthoNormalize(ref normal, ref spineDirection);
RotateTarget(Quaternion.LookRotation((isProne ? spineDirection : -spineDirection), puppetMaster.targetRoot.up));
// Set the target's position
puppetMaster.SampleTargetMappedState();
Vector3 getUpOffset = isProne ? getUpOffsetProne : getUpOffsetSupine;
MoveTarget(puppetMaster.muscles[0].rigidbody.position + puppetMaster.targetRoot.rotation * getUpOffset);
GroundTarget(groundLayers);
getUpPosition = puppetMaster.targetRoot.position;
getupAnimationBlendWeight = 1f;
getUpTargetFixed = false;
break;
}
// Apply the new puppet state
state = newState;
}
/// <summary>
/// Sets the colliders of the puppet to pinned/unpinned materials.
/// </summary>
public void SetColliders(bool unpinned)
{
foreach (Muscle m in puppetMaster.muscles)
{
SetColliders(m, unpinned);
}
}
// Sets colliders of a muscle to puppet or unpinned mode
public void SetColliders(Muscle m, bool unpinned)
{
var props = GetProps(m.props.group);
if (unpinned)
{
foreach (Collider c in m.colliders)
{
c.material = props.unpinnedMaterial != null ? props.unpinnedMaterial : defaults.unpinnedMaterial;
// Enable colliders
if (props.disableColliders) c.enabled = true;
}
}
else
{
foreach (Collider c in m.colliders)
{
c.material = props.puppetMaterial != null ? props.puppetMaterial : defaults.puppetMaterial;
// Enable colliders
if (props.disableColliders) c.enabled = false;
}
}
}
public override void OnMuscleDisconnected(Muscle m)
{
base.OnMuscleDisconnected(m);
SetColliders(m, true);
}
public override void OnMuscleReconnected(Muscle m)
{
base.OnMuscleReconnected(m);
if (m == puppetMaster.muscles[0])
{
SetState(State.Puppet);
}
float f = state == State.Puppet ? 1f : 0f;
m.state.pinWeightMlp = f;
m.state.muscleWeightMlp = f;
m.state.muscleDamperMlp = f;
m.state.maxForceMlp = 1;
m.state.mappingWeightMlp = 1f;
SetColliders(m, state == State.Unpinned);
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6b749367930f7464eba4d8cad81f261d
timeCreated: 1438866601
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,76 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// This is just a commented template for creating new Puppet Behaviours.
/// </summary>
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Behaviours/BehaviourTemplate")]
public class BehaviourTemplate : BehaviourBase {
// Just for demonstrating the intended use of sub-behaviours.
// The sub-behaviours take care of behaviour code reusability.
// While there can be only one active Puppet Behaviour at a time, that active behaviour can use multiple independent and reusable sub-behaviours simultaneously.
// For example the SubBehaviourCOM is responsible for calculating everything about the center of mass and can be used by any behaviour or even other sub-behaviours that need CoM calculations.
// This is the base abstract class for all sub-behaviours.
public SubBehaviourCOM centerOfMass;
// Used by the SubBehaviourCOM
public LayerMask groundLayers;
// Just for demonstrating the intended use of PuppetEvents
public PuppetEvent onLoseBalance;
// A PuppetEvent will be called when the balance angle exceeds this point.
public float loseBalanceAngle = 60f;
protected override void OnInitiate() {
// Initiate something. This is called only once by the PuppetMaster in Start().
// Initiating sub-behaviours. SubBehaviourCOM will update automatically once it has been initiated
centerOfMass.Initiate(this as BehaviourBase, groundLayers);
}
protected override void OnActivate() {
// When this becomes the active behaviour. There can only be one active behaviour.
// Switching behaviours is done by the behaviours themselves, using PuppetEvents.
// Each behaviour should know when it is no longer required and which behaviours to switch to in each case.
}
public override void OnReactivate() {
// Called when the PuppetMaster has been deactivated (by parenting it to an inactive hierarchy or calling SetActive(false)).
}
protected override void OnDeactivate() {
// Called when this behaviour is exited. OnActivate is the place for resetting variables to defaults though.
}
protected override void OnFixedUpdate() {
// Everything happening in the fixed time step.
// Example of using PuppetEvents
if (centerOfMass.angle > loseBalanceAngle) {
// If the angle between Vector3.up and the vector from the center of pressure to the center of mass > loseBalanceangle, lose balance (maybe switch to another behaviour).
onLoseBalance.Trigger(puppetMaster);
}
}
protected override void OnLateUpdate() {
// Everything happening in LateUpdate().
}
protected override void OnMuscleHitBehaviour(MuscleHit hit) {
if (!enabled) return;
// If the muscle has been hit via code using MuscleCollisionBroadcaster.Hit(float unPin, Vector3 force, Vector3 position);
// This is used for shooting based on raycasting instead of physical collisions.
}
protected override void OnMuscleCollisionBehaviour(MuscleCollision m) {
if (!enabled) return;
// If the muscle has collided with something that is on the PuppetMaster's collision layers.
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 762171135dedc40ee90c4c961e36f9a0
timeCreated: 1435605962
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: ffb8680e3e6324a658749c533a23f6d1
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -1,126 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
[System.Serializable]
public class SubBehaviourBalancer : SubBehaviourBase {
/// <summary>
/// Settings for SubBehaviourBalancer.
/// </summary>
[System.Serializable]
public class Settings {
[Tooltip("Ankle joint damper / spring. Increase to make the balancing effect softer.")]
/// <summary>
/// Ankle joint damper / spring. Increase to make the balancing effect softer.
/// </summary>
public float damperForSpring = 1f;
[Tooltip("Multiplier for joint max force.")]
/// <summary>
/// Multiplier for joint max force.
/// </summary>
public float maxForceMlp = 0.05f;
[Tooltip("Multiplier for the inertia tensor. Increasing this will increase the balancing forces.")]
/// <summary>
/// Multiplier for the inertia tensor. Increasing this will increase the balancing forces.
/// </summary>
public float IMlp = 1f;
[Tooltip("Velocity-based prediction.")]
/// <summary>
/// Velocity-based prediction.
/// </summary>
public float velocityF = 0.5f;
[Tooltip("World space offset for the center of pressure. Can be used to make the characer lean in a certain direction.")]
/// <summary>
/// World space offset for the center of pressure. Can be used to make the characer lean in a certain direction.
/// </summary>
public Vector3 copOffset;
[Tooltip("The amount of torque applied to the lower legs to help keep the puppet balanced. Note that this is an external force (not coming from the joints themselves) and might make the simulation seem unnatural.")]
/// <summary>
/// The amount of torque applied to the lower legs to help keep the puppet balanced. Note that this is an external force (not coming from the joints themselves) and might make the simulation seem unnatural.
/// </summary>
public float torqueMlp = 0f;
[Tooltip("Maximum magnitude of the torque applied to the lower legs if 'Torque Mlp' > 0.")]
/// <summary>
/// Maximum magnitude of the torque applied to the lower legs if 'Torque Mlp' > 0.
/// </summary>
public float maxTorqueMag = 45f;
}
public ConfigurableJoint joint { get; private set; }
public Vector3 dir { get; private set;}
public Vector3 dirVel { get; private set;}
public Vector3 cop { get; private set; }
public Vector3 com { get; private set; }
public Vector3 comV { get; private set; }
private Settings settings;
private Rigidbody[] rigidbodies = new Rigidbody[0];
private Transform[] copPoints = new Transform[0];
private PressureSensor pressureSensor;
private Rigidbody Ibody;
private Vector3 I;
private Quaternion toJointSpace = Quaternion.identity;
public void Initiate(BehaviourBase behaviour, Settings settings, Rigidbody Ibody, Rigidbody[] rigidbodies, ConfigurableJoint joint, Transform[] copPoints, PressureSensor pressureSensor) {
this.behaviour = behaviour;
this.settings = settings;
this.Ibody = Ibody;
this.rigidbodies = rigidbodies;
this.joint = joint;
this.copPoints = copPoints;
this.pressureSensor = pressureSensor;
toJointSpace = PhysXTools.ToJointSpace(joint);
behaviour.OnPreFixedUpdate += Solve;
}
void Solve() {
if (copPoints.Length == 0) {
cop = joint.transform.TransformPoint(joint.anchor);
} else {
cop = Vector3.zero;
foreach (Transform copPoint in copPoints) {
cop += copPoint.position;
}
cop /= copPoints.Length;
}
cop += settings.copOffset;
com = PhysXTools.GetCenterOfMass(rigidbodies);
comV = PhysXTools.GetCenterOfMassVelocity(rigidbodies);
dir = com - cop;
dirVel = (com + comV * settings.velocityF) - cop;
Vector3 requiredAcceleration = PhysXTools.GetFromToAcceleration(dirVel, -Physics.gravity);
requiredAcceleration -= Ibody.angularVelocity;
Vector3 torque = requiredAcceleration / Time.fixedDeltaTime;
PhysXTools.ScaleByInertia(ref torque, Ibody.rotation, Ibody.inertiaTensor * settings.IMlp);
torque = Vector3.ClampMagnitude(torque, settings.maxTorqueMag);
bool pressured = pressureSensor == null || !pressureSensor.enabled || pressureSensor.inContact;
if (pressured) {
Ibody.AddTorque(torque * settings.torqueMlp, ForceMode.Force);
joint.targetAngularVelocity = Quaternion.Inverse(toJointSpace) * Quaternion.Inverse(joint.transform.rotation) * torque;
} else {
joint.targetAngularVelocity = Vector3.zero;
}
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6de31dba92eea4c2492989c03b792b73
timeCreated: 1482328947
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,33 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// The sub-behaviours take care of behaviour code reusability.
/// While there can be only one active Puppet Behaviour at a time, that active behaviour can use multiple independent and reusable sub-behaviours simultaneously.
/// For example the SubBehaviourCOM is responsible for calculating everything about the center of mass and can be used by any behaviour or even other sub-behaviours that need CoM calculations.
/// This is the base abstract class for all sub-behaviours.
/// </summary>
[System.Serializable]
public abstract class SubBehaviourBase {
protected BehaviourBase behaviour;
protected static Vector2 XZ(Vector3 v) {
return new Vector2(v.x, v.z);
}
protected static Vector3 XYZ(Vector2 v) {
return new Vector3(v.x, 0f, v.y);
}
protected static Vector3 Flatten(Vector3 v) {
return new Vector3(v.x, 0f, v.z);
}
protected static Vector3 SetY(Vector3 v, float y) {
return new Vector3(v.x, y, v.z);
}
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: a3b383b7d9ca6498692219a366e82ab7
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -1,222 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
[System.Serializable]
public class SubBehaviourCOM: SubBehaviourBase {
[System.Serializable]
public enum Mode {
FeetCentroid,
CenterOfPressure
}
public Mode mode;
public float velocityDamper = 1f;
public float velocityLerpSpeed = 5f;
public float velocityMax = 1f;
public float centerOfPressureSpeed = 5f;
public Vector3 offset;
public Vector3 position { get; private set; }
public Vector3 direction { get; private set; }
public float angle { get; private set; }
public Vector3 velocity { get; private set; }
public Vector3 centerOfPressure { get; private set; }
public Quaternion rotation { get; private set; }
public Quaternion inverseRotation { get; private set; }
public bool isGrounded { get; private set; }
public float lastGroundedTime { get; private set; }
[HideInInspector] public bool[] groundContacts;
[HideInInspector] public Vector3[] groundContactPoints;
private LayerMask groundLayers;
public void Initiate(BehaviourBase behaviour, LayerMask groundLayers) {
this.behaviour = behaviour;
this.groundLayers = groundLayers;
rotation = Quaternion.identity;
groundContacts = new bool[behaviour.puppetMaster.muscles.Length];
groundContactPoints = new Vector3[groundContacts.Length];
behaviour.OnPreActivate += OnPreActivate;
behaviour.OnPreLateUpdate += OnPreLateUpdate;
behaviour.OnPreDeactivate += OnPreDeactivate;
behaviour.OnPreMuscleCollision += OnPreMuscleCollision;
behaviour.OnPreMuscleCollisionExit += OnPreMuscleCollisionExit;
behaviour.OnHierarchyChanged += OnHierarchyChanged;
}
#region Behaviour Delegates
private void OnHierarchyChanged() {
System.Array.Resize (ref groundContacts, behaviour.puppetMaster.muscles.Length);
System.Array.Resize (ref groundContactPoints, behaviour.puppetMaster.muscles.Length);
}
private void OnPreMuscleCollision(MuscleCollision c) {
if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer)) return;
if (c.collision.contacts.Length == 0) return;
lastGroundedTime = Time.time;
groundContacts[c.muscleIndex] = true;
if (mode == Mode.CenterOfPressure) groundContactPoints[c.muscleIndex] = GetCollisionCOP(c.collision);
}
private void OnPreMuscleCollisionExit(MuscleCollision c) {
if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer)) return;
groundContacts[c.muscleIndex] = false;
groundContactPoints[c.muscleIndex] = Vector3.zero;
}
private void OnPreActivate() {
position = GetCenterOfMass();
centerOfPressure = GetFeetCentroid();
direction = position - centerOfPressure;
angle = Vector3.Angle(direction, Vector3.up);
velocity = Vector3.zero;
}
private void OnPreLateUpdate() {
// Ground contact
isGrounded = IsGrounded();
// COP
if (mode == Mode.FeetCentroid || !isGrounded) {
centerOfPressure = GetFeetCentroid();
} else {
Vector3 centerOfPressureTarget = isGrounded? GetCenterOfPressure(): GetFeetCentroid();
centerOfPressure = centerOfPressureSpeed <= 02? centerOfPressureTarget: Vector3.Lerp(centerOfPressure, centerOfPressureTarget, Time.deltaTime * centerOfPressureSpeed);
}
// COM
position = GetCenterOfMass();
// COM Velocity
Vector3 velocityPosition = GetCenterOfMassVelocity();
Vector3 velocityTarget = velocityPosition - position;
velocityTarget.y = 0f;
velocityTarget = Vector3.ClampMagnitude(velocityTarget, velocityMax);
// Add velocity to position
velocity = velocityLerpSpeed <= 0f? velocityTarget: Vector3.Lerp(velocity, velocityTarget, Time.deltaTime * velocityLerpSpeed);
position += velocity * velocityDamper;
position += behaviour.puppetMaster.targetRoot.rotation * offset;
// Calculate COM direction, rotation and angle
direction = position - centerOfPressure;
rotation = Quaternion.FromToRotation(Vector3.up, direction);
inverseRotation = Quaternion.Inverse(rotation);
angle = Quaternion.Angle(Quaternion.identity, rotation);
}
private void OnPreDeactivate() {
velocity = Vector3.zero;
}
#endregion Behaviour Delegates
private Vector3 GetCollisionCOP(Collision collision) {
Vector3 sum = Vector3.zero;
for (int i = 0; i < collision.contacts.Length; i++) {
sum += collision.contacts[i].point;
}
return sum / (float)collision.contacts.Length;
}
private bool IsGrounded() {
for (int i = 0; i < groundContacts.Length; i++) {
if (groundContacts[i]) return true;
}
return false;
}
private Vector3 GetCenterOfMass() {
Vector3 CoM = Vector3.zero;
float c = 0f;
foreach (Muscle m in behaviour.puppetMaster.muscles) {
CoM += m.rigidbody.worldCenterOfMass * m.rigidbody.mass;
c += m.rigidbody.mass;
}
return CoM /= c;
}
private Vector3 GetCenterOfMassVelocity() {
Vector3 CoM = Vector3.zero;
float c = 0f;
foreach (Muscle m in behaviour.puppetMaster.muscles) {
CoM += m.rigidbody.worldCenterOfMass * m.rigidbody.mass;
CoM += m.rigidbody.velocity * m.rigidbody.mass;
c += m.rigidbody.mass;
}
return CoM /= c;
}
private Vector3 GetMomentum() {
Vector3 sum = Vector3.zero;
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.velocity * behaviour.puppetMaster.muscles[i].rigidbody.mass;
}
return sum;
}
private Vector3 GetCenterOfPressure() {
Vector3 sum = Vector3.zero;
int contacts = 0;
for (int i = 0; i < groundContacts.Length; i++) {
if (groundContacts[i]) {
sum += groundContactPoints[i];
contacts ++;
}
}
sum /= (float)contacts;
return sum;
}
private Vector3 GetFeetCentroid() {
Vector3 sum = Vector3.zero;
int contacts = 0;
/*
int feetGrounded = 0;
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot && groundContacts[i]) feetGrounded ++;
}
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot) {
if (feetGrounded == 0 || (feetGrounded > 0 && groundContacts[i])) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.worldCenterOfMass;
contacts ++;
}
}
}
*/
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.worldCenterOfMass;
contacts ++;
}
}
sum /= (float)contacts;
return sum;
}
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 0763c4b89286d49acaa9fdf15769756f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -1,87 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// Booster for BehaviourPuppet. Can be used to enhance puppet collision resistance and/or dealing damage to other puppets.
/// </summary>
[System.Serializable]
public class Booster {
[Tooltip("If true, all the muscles will be boosted and the 'Muscles' and 'Groups' properties below will be ignored.")]
/// <summary>
/// If true, all the muscles will be boosted and the 'Muscles' and 'Groups' properties below will be ignored.
/// </summary>
public bool fullBody;
[Tooltip("Muscles to boost. Used only when 'Full Body' is false.")]
/// <summary>
/// Muscles to boost. Used only when 'Full Body' is false.
/// </summary>
public ConfigurableJoint[] muscles = new ConfigurableJoint[0];
[Tooltip("Muscle groups to boost. Used only when 'Full Body' is false.")]
/// <summary>
/// Muscle groups to boost. Used only when 'Full Body' is false.
/// </summary>
public Muscle.Group[] groups = new Muscle.Group[0];
[Tooltip("Immunity to apply to the muscles. If muscle immunity is 1, it can not be damaged.")]
/// <summary>
/// Immunity to apply to the muscles. If muscle immunity is 1, it can not be damaged.
/// </summary>
[Range(0f, 1f)] public float immunity;
[Tooltip("Impulse multiplier to be applied to the muscles. This makes them deal more damage to other puppets.")]
/// <summary>
/// Impulse multiplier to be applied to the muscles. This makes them deal more damage to other puppets.
/// </summary>
public float impulseMlp;
[Tooltip("Falloff for parent muscles (power of kinship degree).")]
/// <summary>
/// Falloff for parent muscles (power of kinship degree).
/// </summary>
public float boostParents;
[Tooltip("Falloff for child muscles (power of kinship degree).")]
/// <summary>
/// Falloff for child muscles (power of kinship degree).
/// </summary>
public float boostChildren;
[Tooltip("This does nothing on it's own, you can use it in a 'yield return new WaitForseconds(delay);' call.")]
/// <summary>
/// This does nothing on it's own, you can use it in a 'yield return new WaitForseconds(delay);' call.
/// </summary>
public float delay;
/// <summary>
/// Boost the puppet's performance.
/// </summary>
public void Boost(BehaviourPuppet puppet) {
if (fullBody) puppet.Boost(immunity, impulseMlp);
else {
// Muscles
foreach (ConfigurableJoint joint in muscles) {
for (int i = 0; i < puppet.puppetMaster.muscles.Length; i++) {
if (puppet.puppetMaster.muscles[i].joint == joint) {
puppet.Boost(i, immunity, impulseMlp, boostParents, boostChildren);
break;
}
}
}
// Groups
foreach (Muscle.Group group in groups) {
for (int i = 0; i < puppet.puppetMaster.muscles.Length; i++) {
if (puppet.puppetMaster.muscles[i].props.group == group) {
puppet.Boost(i, immunity, impulseMlp, boostParents, boostChildren);
}
}
}
}
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 18beedbb70631428ba7cf3532df5cc35
timeCreated: 1438861024
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,23 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
public class JointBreakBroadcaster : MonoBehaviour {
/// <summary>
/// The PuppetMaster that this muscle belongs to.
/// </summary>
[SerializeField][HideInInspector] public PuppetMaster puppetMaster;
/// <summary>
/// The index of this muscle in the PuppetMaster.muscles array.
/// </summary>
[SerializeField][HideInInspector] public int muscleIndex;
void OnJointBreak() {
if (!enabled) return;
puppetMaster.RemoveMuscleRecursive(puppetMaster.muscles[muscleIndex].joint, true, true, MuscleRemoveMode.Numb);
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: a77f3049782644ff8803c8b79f2fa253
timeCreated: 1471636440
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
File diff suppressed because it is too large Load Diff
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 36692d5cb45554f5997a72cd4e2c92c8
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -1,125 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// All the required information when a muscle collides with something.
/// </summary>
public struct MuscleCollision {
/// <summary>
/// The index of the colliding muscle in the PuppetMaster.muscles array.
/// </summary>
public int muscleIndex;
/// <summary>
/// The collision from OnCollisionEnter/Stay/Exit.
/// </summary>
public Collision collision;
public bool isStay;
public MuscleCollision(int muscleIndex, Collision collision, bool isStay = false) {
this.muscleIndex = muscleIndex;
this.collision = collision;
this.isStay = isStay;
}
}
/// <summary>
/// Hitting muscles via code, usually by raycasting.
/// </summary>
public struct MuscleHit {
/// <summary>
/// The index of the colliding muscle in the PuppetMaster.muscles array.
/// </summary>
public int muscleIndex;
/// <summary>
/// How much should the muscle be unpinned by the hit?
/// </summary>
public float unPin;
/// <summary>
/// The force to add to the muscle's Rigidbody.
/// </summary>
public Vector3 force;
/// <summary>
/// The world space hit point.
/// </summary>
public Vector3 position;
public MuscleHit(int muscleIndex, float unPin, Vector3 force, Vector3 position) {
this.muscleIndex = muscleIndex;
this.unPin = unPin;
this.force = force;
this.position = position;
}
}
/// <summary>
/// Filters and broadcasts collisions with the Muscles to the Puppet Behaviours.
/// </summary>
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Muscle Collision Broadcaster")]
public class MuscleCollisionBroadcaster : MonoBehaviour {
/// <summary>
/// The PuppetMaster that this muscle belongs to.
/// </summary>
[SerializeField][HideInInspector] public PuppetMaster puppetMaster;
/// <summary>
/// The index of this muscle in the PuppetMaster.muscles array.
/// </summary>
[SerializeField][HideInInspector] public int muscleIndex;
private const string onMuscleHit = "OnMuscleHit";
private const string onMuscleCollision = "OnMuscleCollision";
private const string onMuscleCollisionExit = "OnMuscleCollisionExit";
private MuscleCollisionBroadcaster otherBroadcaster;
public void Hit(float unPin, Vector3 force, Vector3 position) {
if (!enabled) return;
foreach (BehaviourBase behaviour in puppetMaster.behaviours) {
behaviour.OnMuscleHit(new MuscleHit(muscleIndex, unPin, force, position));
}
}
void OnCollisionEnter(Collision collision) {
if (!enabled) return;
if (puppetMaster == null) return;
if (collision.collider.transform.root == transform.root) return; // @todo make sure characters are not stacked to the same root
if (puppetMaster.muscles[muscleIndex].state.isDisconnected) return;
foreach (BehaviourBase behaviour in puppetMaster.behaviours) {
behaviour.OnMuscleCollision(new MuscleCollision(muscleIndex, collision));
}
}
void OnCollisionStay(Collision collision) {
if (!enabled) return;
if (puppetMaster == null) return;
if (PuppetMasterSettings.instance != null && !PuppetMasterSettings.instance.collisionStayMessages) return;
if (collision.collider.transform.root == transform.root) return;
if (puppetMaster.muscles[muscleIndex].state.isDisconnected) return;
foreach (BehaviourBase behaviour in puppetMaster.behaviours) {
behaviour.OnMuscleCollision(new MuscleCollision(muscleIndex, collision, true));
}
}
void OnCollisionExit(Collision collision) {
if (!enabled) return;
if (puppetMaster == null) return;
if (PuppetMasterSettings.instance != null && !PuppetMasterSettings.instance.collisionExitMessages) return;
if (collision.collider.transform.root == transform.root) return;
if (puppetMaster.muscles[muscleIndex].state.isDisconnected) return;
foreach (BehaviourBase behaviour in puppetMaster.behaviours) {
behaviour.OnMuscleCollisionExit(new MuscleCollision(muscleIndex, collision));
}
}
}
}
@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 373554a5ccbba4f58a126a7bb3910c82
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -1,276 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// Library of static helper methods for working with PhysX Rigidbodies.
/// </summary>
public static class PhysXTools {
/// <summary>
/// Predicts unconstrained Rigidbody (ignoring collisions and joints) position and rotation after specified PhysX steps.
/// </summary>
public static void Predict(Rigidbody r, int steps, out Vector3 position, out Quaternion rotation)
{
Predict(r, steps, out position, out rotation, Physics.gravity, r.drag, r.angularDrag);
}
/// <summary>
/// Predicts unconstrained Rigidbody (ignoring collisions and joints) position and rotation after specified PhysX steps using custom gravity, drag and angularDrag settings.
/// </summary>
public static void Predict(Rigidbody r, int steps, out Vector3 position, out Quaternion rotation, Vector3 gravity, float drag, float angularDrag)
{
position = r.position;
rotation = r.rotation;
Vector3 velocity = r.velocity;
Vector3 angularVelocity = r.angularVelocity;
for (int i = 0; i < steps; i++)
{
Predict(ref position, ref rotation, ref velocity, ref angularVelocity, gravity, drag, angularDrag);
}
}
/// <summary>
/// Predicts a single PhysX step of an unconstrained Rigidbody (ignoring collisions and joints) position and rotation using custom gravity, drag and angularDrag settings.
/// </summary>
public static void Predict(ref Vector3 position, ref Quaternion rotation, ref Vector3 velocity, ref Vector3 angularVelocity, Vector3 gravity, float drag, float angularDrag)
{
velocity += gravity * Time.fixedDeltaTime;
velocity -= velocity * drag * Time.fixedDeltaTime;
angularVelocity -= angularVelocity * angularDrag * Time.fixedDeltaTime;
Vector3 deltaPos = velocity * Time.fixedDeltaTime;
Vector3 deltaRot = angularVelocity * Time.fixedDeltaTime * Mathf.Rad2Deg;
position += deltaPos;
rotation *= Quaternion.Euler(deltaRot);
}
/// <summary>
/// Gets the center of mass of a puppet.
/// </summary>
public static Vector3 GetCenterOfMass(PuppetMaster puppet) {
Vector3 CoM = Vector3.zero;
float c = 0f;
for (int i = 0; i < puppet.muscles.Length; i++) {
if (puppet.muscles[i].joint.gameObject.activeInHierarchy) {
CoM += puppet.muscles[i].rigidbody.worldCenterOfMass * puppet.muscles[i].rigidbody.mass;
c += puppet.muscles[i].rigidbody.mass;
}
}
return CoM / c;
}
/// <summary>
/// Gets the center of mass of an array of Rigidbodies.
/// </summary>
public static Vector3 GetCenterOfMass(Rigidbody[] rigidbodies) {
Vector3 CoM = Vector3.zero;
float c = 0f;
for (int i = 0; i < rigidbodies.Length; i++) {
if (rigidbodies[i].gameObject.activeInHierarchy) {
CoM += rigidbodies[i].worldCenterOfMass * rigidbodies[i].mass;
c += rigidbodies[i].mass;
}
}
return CoM / c;
}
/// <summary>
/// Gets the velocity of the center of mass of an array of Rigidbodies.
/// </summary>
public static Vector3 GetCenterOfMassVelocity(Rigidbody[] rigidbodies) {
Vector3 CoM = Vector3.zero;
float c = 0f;
for (int i = 0; i < rigidbodies.Length; i++) {
if (rigidbodies[i].gameObject.activeInHierarchy) {
CoM += rigidbodies[i].velocity * rigidbodies[i].mass;
c += rigidbodies[i].mass;
}
}
return CoM / c;
}
/// <summary>
/// Divides an angular acceleration by an inertia tensor.
/// </summary>
public static void DivByInertia(ref Vector3 v, Quaternion rotation, Vector3 inertiaTensor) {
v = rotation * Div(Quaternion.Inverse(rotation) * v, inertiaTensor);
}
/// <summary>
/// Scales an angular acceleration by an inertia tensor
/// </summary>
public static void ScaleByInertia(ref Vector3 v, Quaternion rotation, Vector3 inertiaTensor) {
v = rotation * Vector3.Scale(Quaternion.Inverse(rotation) * v, inertiaTensor);
}
/// <summary>
/// Returns the angular acceleration from one vector to another.
/// </summary>
public static Vector3 GetFromToAcceleration(Vector3 fromV, Vector3 toV) {
Quaternion fromTo = Quaternion.FromToRotation(fromV, toV);
float requiredAccelerationDeg = 0f;
Vector3 axis = Vector3.zero;
fromTo.ToAngleAxis(out requiredAccelerationDeg, out axis);
Vector3 requiredAcceleration = requiredAccelerationDeg * axis * Mathf.Deg2Rad;
return requiredAcceleration / Time.fixedDeltaTime;
}
/// <summary>
/// Returns the angular acceleration from "fromR" to "toR."
/// Does not guarantee full accuracy with rotations around multiple axes).
/// </summary>
public static Vector3 GetAngularAcceleration(Quaternion fromR, Quaternion toR) {
Vector3 axis = Vector3.Cross(fromR * Vector3.forward, toR * Vector3.forward);
Vector3 axis2 = Vector3.Cross(fromR * Vector3.up, toR * Vector3.up);
float angle = Quaternion.Angle(fromR, toR);
Vector3 acc = Vector3.Normalize(axis + axis2) * angle * Mathf.Deg2Rad;
return acc / Time.fixedDeltaTime;
}
/// <summary>
/// Adds torque to the Ridigbody that accelerates it from it's current rotation to another using any force mode.
/// </summary>
public static void AddFromToTorque(Rigidbody r, Quaternion toR, ForceMode forceMode) {
Vector3 requiredAcceleration = GetAngularAcceleration(r.rotation, toR); // Acceleration required for a single solver step
requiredAcceleration -= r.angularVelocity; // Compensate for angular velocity
switch (forceMode) {
case ForceMode.Acceleration:
r.AddTorque(requiredAcceleration / Time.fixedDeltaTime, forceMode);
break;
case ForceMode.Force:
Vector3 force = requiredAcceleration / Time.fixedDeltaTime;
ScaleByInertia(ref force, r.rotation, r.inertiaTensor);
r.AddTorque(force, forceMode);
break;
case ForceMode.Impulse:
Vector3 impulse = requiredAcceleration;
ScaleByInertia(ref impulse, r.rotation, r.inertiaTensor);
r.AddTorque(impulse, forceMode);
break;
case ForceMode.VelocityChange:
r.AddTorque(requiredAcceleration, forceMode);
break;
}
}
/// <summary>
/// Adds torque to the Ridigbody that accelerates it from one direction to another using any force mode.
/// </summary>
public static void AddFromToTorque(Rigidbody r, Vector3 fromV, Vector3 toV, ForceMode forceMode) {
Vector3 requiredAcceleration = GetFromToAcceleration(fromV, toV); // Acceleration required for a single solver step
requiredAcceleration -= r.angularVelocity; // Compensate for angular velocity
switch(forceMode) {
case ForceMode.Acceleration:
r.AddTorque(requiredAcceleration / Time.fixedDeltaTime, forceMode);
break;
case ForceMode.Force:
Vector3 force = requiredAcceleration / Time.fixedDeltaTime;
ScaleByInertia(ref force, r.rotation, r.inertiaTensor);
r.AddTorque(force, forceMode);
break;
case ForceMode.Impulse:
Vector3 impulse = requiredAcceleration;
ScaleByInertia(ref impulse, r.rotation, r.inertiaTensor);
r.AddTorque(impulse, forceMode);
break;
case ForceMode.VelocityChange:
r.AddTorque(requiredAcceleration, forceMode);
break;
}
}
/// <summary>
/// Adds a force to a Rigidbody that gets it from one place to another within a single simulation step using any force mode.
/// </summary>
public static void AddFromToForce(Rigidbody r, Vector3 fromV, Vector3 toV, ForceMode forceMode) {
Vector3 requiredAcceleration = GetLinearAcceleration(fromV, toV);
requiredAcceleration -= r.velocity;
switch(forceMode) {
case ForceMode.Acceleration:
r.AddForce(requiredAcceleration / Time.fixedDeltaTime, forceMode);
break;
case ForceMode.Force:
Vector3 force = requiredAcceleration / Time.fixedDeltaTime;
force *= r.mass;
r.AddForce(force, forceMode);
break;
case ForceMode.Impulse:
Vector3 impulse = requiredAcceleration;
impulse *= r.mass;
r.AddForce(impulse, forceMode);
break;
case ForceMode.VelocityChange:
r.AddForce(requiredAcceleration, forceMode);
break;
}
}
/// <summary>
/// Returns the linear acceleration from one point to another.
/// </summary>
public static Vector3 GetLinearAcceleration(Vector3 fromPoint, Vector3 toPoint) {
return (toPoint - fromPoint) / Time.fixedDeltaTime;
}
/// <summary>
/// The rotation expressed by the joint's axis and secondary axis
/// </summary>
public static Quaternion ToJointSpace(ConfigurableJoint joint) {
Vector3 forward = Vector3.Cross (joint.axis, joint.secondaryAxis);
Vector3 up = Vector3.Cross (forward, joint.axis);
return Quaternion.LookRotation (forward, up);
}
/// <summary>
/// Calculates the inertia tensor for a cuboid.
/// </summary>
public static Vector3 CalculateInertiaTensorCuboid(Vector3 size, float mass) {
float x2 = size.x * size.x;
float y2 = size.y * size.y;
float z2 = size.z * size.z;
float mlp = 1f/12f * mass;
return new Vector3(
mlp * (y2 + z2),
mlp * (x2 + z2),
mlp * (x2 + y2));
}
/// <summary>
/// Divide all the values in v by their respective values in v2.
/// </summary>
public static Vector3 Div(Vector3 v, Vector3 v2) {
return new Vector3(v.x / v2.x, v.y / v2.y, v.z / v2.z);
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 8f746daf167df400c968e119d42a30a5
timeCreated: 1470733461
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,79 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
public class PressureSensor : MonoBehaviour {
public bool visualize;
public LayerMask layers;
public Vector3 center { get; private set; }
public bool inContact { get; private set; }
public Vector3 bottom { get; private set; }
public Rigidbody r { get; private set; }
private bool fixedFrame;
private Vector3 P;
private int count;
void Awake() {
r = GetComponent<Rigidbody>();
center = transform.position;
}
void OnCollisionEnter(Collision c) {
ProcessCollision(c);
}
void OnCollisionStay(Collision c) {
ProcessCollision(c);
}
void OnCollisionExit(Collision c) {
inContact = false;
}
void FixedUpdate() {
fixedFrame = true;
if (!r.IsSleeping()) {
P = Vector3.zero;
count = 0;
}
}
void LateUpdate() {
if (fixedFrame) {
if (count > 0) {
center = P / count;
//center = Vector3.Lerp(transform.position + transform.rotation * bottom, center, 0.0f);
}
fixedFrame = false;
}
}
private void ProcessCollision(Collision c) {
if (!LayerMaskExtensions.Contains(layers, c.gameObject.layer)) return;
Vector3 collisionCenter = Vector3.zero;
for (int i = 0; i < c.contacts.Length; i++) {
collisionCenter += c.contacts[i].point;
}
collisionCenter /= c.contacts.Length;
P += collisionCenter;// * pressure // TODO process each collision based on it's pressure
count++;
inContact = true;
}
void OnDrawGizmos() {
if (!visualize) return;
Gizmos.DrawSphere(center, 0.1f);
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 71460163d1998435b923a037e2f52ee9
timeCreated: 1470245983
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,204 +0,0 @@
using UnityEngine;
using System.Collections;
using RootMotion;
namespace RootMotion.Dynamics {
/// <summary>
/// Automated prop picking up/dropping for the PuppetMaster.
/// </summary>
public abstract class Prop : MonoBehaviour {
#region User Interface
[Tooltip("This has no other purpose but helping you distinguish props by PropRoot.currentProp.propType.")]
/// <summary>
/// This has no other purpose but helping you distinguish PropRoot.currentProp by type.
/// </summary>
public int propType;
[LargeHeader("Muscle")]
[Tooltip("The Muscle of this prop.")]
/// <summary>
/// The Muscle of this prop.
/// </summary>
public ConfigurableJoint muscle;
/*
[Tooltip("Ignore collisions with these bones (Humanoid only)")]
/// <summary>
/// Ignore collisions with these Humanoid bones. This will automatically find the Muscles for the Muscle Props Internal Collision Ignores below when the prop is picked up.
/// </summary>
public HumanBodyBones[] internalCollisionIgnores;
*/
[Tooltip("The muscle properties that will be applied to the Muscle on pickup.")]
/// <summary>
/// The muscle properties that will be applied to the Muscle.
/// </summary>
public Muscle.Props muscleProps = new Muscle.Props();
[Tooltip("If true, this prop's layer will be forced to PuppetMaster layer and target's layer forced to PuppetMaster's Target Root's layer when the prop is picked up.")]
/// <summary>
/// If true, this prop's layer will be forced to PuppetMaster layer and target's layer forced to PuppetMaster's Target Root's layer when the prop is picked up.
/// </summary>
public bool forceLayers = true;
[LargeHeader("Additional Pin")]
[Tooltip("Optinal additional pin, useful for long melee weapons that would otherwise require a lot of muscle force and solver iterations to be swinged quickly. Should normally be without any colliders attached. The position of the pin, it's mass and the pin weight will effect how the prop will handle.")]
/// <summary>
/// Optinal additional pin, useful for long melee weapons that would otherwise require a lot of muscle force and solver iterations to be swinged quickly. Should normally be without any colliders attached. The position of the pin, it's mass and the pin weight will effect how the prop will handle.
/// </summary>
public ConfigurableJoint additionalPin;
[Tooltip("Target Transform for the additional pin.")]
/// <summary>
/// Target Transform for the additional pin.
/// </summary>
public Transform additionalPinTarget;
[Tooltip("The pin weight of the additional pin. Increasing this weight will make the prop follow animation better, but will increase jitter when colliding with objects.")]
/// <summary>
/// The pin weight of the additional pin. Increasing this weight will make the prop follow animation better, but will increase jitter when colliding with objects.
/// </summary>
[Range(0f, 1f)] public float additionalPinWeight = 1f;
[LargeHeader("Materials")]
[Tooltip("If assigned, sets prop colliders to this PhysicMaterial when picked up.")]
/// <summary>
/// If assigned, sets prop colliders to this PhysicMaterial when picked up.
/// </summary>
public PhysicMaterial pickedUpMaterial;
[Tooltip("If assigned, sets prop colliders to this PhysicMaterial when dropped.")]
/// <summary>
/// If assigned, sets prop colliders to this PhysicMaterial when dropped.
/// </summary>
public PhysicMaterial droppedMaterial;
/// <summary>
/// Is this prop picked up and connected to a PropRoot?
/// </summary>
public bool isPickedUp { get { return propRoot != null; }}
/// <summary>
/// Returns the PropRoot that this prop is connected to if it is picked up. If this returns null, the prop is not picked up.
/// </summary>
public PropRoot propRoot { get; private set; }
#endregion User Interface
// Picking up/dropping props is done by simply changing PropRoot.currentProp
public void PickUp(PropRoot propRoot) {
muscle.xMotion = xMotion;
muscle.yMotion = yMotion;
muscle.zMotion = zMotion;
muscle.angularXMotion = angularXMotion;
muscle.angularYMotion = angularYMotion;
muscle.angularZMotion = angularZMotion;
this.propRoot = propRoot;
muscle.gameObject.layer = propRoot.puppetMaster.gameObject.layer;
foreach (Collider c in colliders) {
if (!c.isTrigger) c.gameObject.layer = muscle.gameObject.layer;
}
SetMaterial(pickedUpMaterial);
OnPickUp(propRoot);
}
// Picking up/dropping props is done by simply changing PropRoot.currentProp
public void Drop() {
this.propRoot = null;
SetMaterial(droppedMaterial);
OnDrop();
}
public void StartPickedUp(PropRoot propRoot) {
this.propRoot = propRoot;
}
public bool initiated { get; private set; }
protected virtual void OnPickUp(PropRoot propRoot) {}
protected virtual void OnDrop() {}
protected virtual void OnStart() {}
private ConfigurableJointMotion xMotion, yMotion, zMotion, angularXMotion, angularYMotion, angularZMotion;
private Collider[] colliders = new Collider[0];
void Start() {
Debug.LogWarning("PropRoot and Prop system is deprecated. Please see the 'Prop' demo to learn about the new easier and much more performance-efficient PropMuscle and PuppetMasterProp system.", transform);
if (transform.position != muscle.transform.position) {
Debug.LogError("Prop target position must match exactly with it's muscle's position!", transform);
}
xMotion = muscle.xMotion;
yMotion = muscle.yMotion;
zMotion = muscle.zMotion;
angularXMotion = muscle.angularXMotion;
angularYMotion = muscle.angularYMotion;
angularZMotion = muscle.angularZMotion;
colliders = muscle.GetComponentsInChildren<Collider>();
if (!isPickedUp) ReleaseJoint();
OnStart();
initiated = true;
}
private void ReleaseJoint() {
muscle.connectedBody = null;
muscle.targetRotation = Quaternion.identity;
JointDrive j = new JointDrive();
j.positionSpring = 0f;
#if UNITY_5_2
j.mode = JointDriveMode.None;
#endif
muscle.slerpDrive = j;
muscle.xMotion = ConfigurableJointMotion.Free;
muscle.yMotion = ConfigurableJointMotion.Free;
muscle.zMotion = ConfigurableJointMotion.Free;
muscle.angularXMotion = ConfigurableJointMotion.Free;
muscle.angularYMotion = ConfigurableJointMotion.Free;
muscle.angularZMotion = ConfigurableJointMotion.Free;
}
private void SetMaterial(PhysicMaterial material)
{
if (material == null) return;
foreach (Collider c in colliders)
{
c.sharedMaterial = material;
}
}
// Just making sure this GameObject's position and rotation matches with the muscle's in the Editor.
void OnDrawGizmos() {
if (muscle == null) return;
if (Application.isPlaying) return;
transform.position = muscle.transform.position;
transform.rotation = muscle.transform.rotation;
if (additionalPinTarget != null && additionalPin != null) {
additionalPinTarget.position = additionalPin.transform.position;
}
muscleProps.group = Muscle.Group.Prop;
}
}
}
@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6a611779f964f43249e427f512484a80
timeCreated: 1431502619
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -1,248 +0,0 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics
{
/// <summary>
/// Muscle that PuppetMasterProps can be attached to.
/// </summary>
public class PropMuscle : MonoBehaviour
{
[SerializeField] [HideInInspector] public PuppetMaster puppetMaster;
[Tooltip("The PuppetMasterProp currently held by this Prop Muscle. To pick up a prop, just assign it as propMuscle.currentProp. To drop, set propMuscle.currentProp to null. Replacing this value with another prop drops any previously held props.")]
/// <summary>
/// The PuppetMasterProp currently held by this Prop Muscle. To pick up a prop, just assign it as propMuscle.currentProp. To drop, set propMuscle.currentProp to null. Replacing this value with another prop drops any previously held props.
/// </summary>
public PuppetMasterProp currentProp;
[LargeHeader("Additional Pin")]
[Tooltip("Offset of the additional pin from this Prop Muscle in local space.")]
/// <summary>
/// Offset of the additional pin from this Prop Muscle in local space.
/// </summary>
public Vector3 additionalPinOffset = Vector3.forward;
public Muscle muscle
{
get
{
if (_muscle == null) _muscle = puppetMaster.GetMuscle(GetComponent<ConfigurableJoint>());
return _muscle;
}
}
/// <summary>
/// The prop that is actually connected to this PropMuscle. Null if none.
/// </summary>
public PuppetMasterProp activeProp { get; private set; }
/// <summary>
/// Delegate used when picking up and dropping props.
/// </summary>
/// <param name="prop"></param>
public delegate void PropDelegate(PuppetMasterProp prop);
/// <summary>
/// Called after a prop has been picked up by this PropMuscle.
/// </summary>
public PropDelegate OnPickUpProp;
/// <summary>
/// Called after a prop is dropped by this PropMuscle.
/// </summary>
public PropDelegate OnDropProp;
private Muscle _muscle;
private PuppetMasterProp lastProp;
private Vector3 targetDefaultLocalPos;
private Vector3 lastAdditionalPinOffset;
/// <summary>
/// Adding additional pin at runtime.
/// </summary>
public bool AddAdditionalPin()
{
if (!puppetMaster.initiated)
{
Debug.LogError("Can not call AddAdditionalPin on an uninitiated PuppetMaster.", transform);
return false;
}
if (muscle.additionalPin != null) return false;
var addGO = new GameObject("Additional Pin");
addGO.gameObject.layer = gameObject.layer;
addGO.transform.parent = transform;
addGO.transform.localPosition = additionalPinOffset;
addGO.transform.localRotation = Quaternion.identity;
lastAdditionalPinOffset = additionalPinOffset;
addGO.AddComponent<Rigidbody>();
var joint = addGO.AddComponent<ConfigurableJoint>();
joint.connectedBody = muscle.joint.GetComponent<Rigidbody>();
joint.autoConfigureConnectedAnchor = false;
joint.connectedAnchor = additionalPinOffset;
joint.xMotion = ConfigurableJointMotion.Locked;
joint.yMotion = ConfigurableJointMotion.Locked;
joint.zMotion = ConfigurableJointMotion.Locked;
joint.angularXMotion = ConfigurableJointMotion.Locked;
joint.angularYMotion = ConfigurableJointMotion.Locked;
joint.angularZMotion = ConfigurableJointMotion.Locked;
var addTargetGO = new GameObject("Additional Pin Target");
addTargetGO.layer = muscle.target.gameObject.layer;
addTargetGO.transform.parent = muscle.target;
addTargetGO.transform.position = addGO.transform.position;
addTargetGO.transform.rotation = addGO.transform.rotation;
muscle.additionalPin = joint;
muscle.additionalPinTarget = addTargetGO.transform;
muscle.InitiateAdditionalPin();
//muscle.additionalPin.gameObject.hideFlags = HideFlags.HideInHierarchy;
//muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.HideInHierarchy;
return true;
}
/// <summary>
/// Removing additional pin at runtime
/// </summary>
public bool RemoveAdditionalPin()
{
if (!puppetMaster.initiated)
{
Debug.LogError("Can not call RemoveAdditionalPin on an uninitiated PuppetMaster.", transform);
return false;
}
if (muscle.additionalPin == null) return false;
//muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
//muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
Destroy(muscle.additionalPin.gameObject);
Destroy(muscle.additionalPinTarget.gameObject);
muscle.additionalPin = null;
muscle.additionalPinTarget = null;
return true;
}
public void OnInitiate()
{
muscle.isPropMuscle = true;
if (currentProp == null && activeProp == null) puppetMaster.DisconnectMuscleRecursive(muscle.index, MuscleDisconnectMode.Sever, true);
}
public void TakeOver()
{
currentProp = null;
lastProp = null;
activeProp = null;
puppetMaster.DisconnectMuscleRecursive(muscle.index, MuscleDisconnectMode.Sever, true);
}
public void OnUpdate()
{
if (currentProp != lastProp && !puppetMaster.IsDisconnecting(muscle.index) && !puppetMaster.IsReconnecting(muscle.index))
{
// Drop any previously held props
if (lastProp != null)
{
lastProp.Drop(puppetMaster, muscle.index);
activeProp = null;
if (OnDropProp != null) OnDropProp(lastProp);
}
if (currentProp != null)
{
// Take over if currentProp is held by anoth prop muscle
foreach (PropMuscle otherPropMuscle in puppetMaster.propMuscles)
{
if (otherPropMuscle != this)
{
if (otherPropMuscle.currentProp == currentProp) otherPropMuscle.TakeOver();
}
}
// Reconnect Prop Muscle
if (muscle.state.isDisconnected)
{
puppetMaster.ReconnectMuscleRecursive(muscle.index);
}
// Pick up the new prop
currentProp.PickUp(puppetMaster, muscle.index);
muscle.rigidbody.ResetInertiaTensor();
activeProp = currentProp;
if (OnPickUpProp != null) OnPickUpProp(currentProp);
}
else
{
// If no current prop, disconnect this prop muscle.
puppetMaster.DisconnectMuscleRecursive(muscle.index, MuscleDisconnectMode.Sever, true);
}
lastProp = currentProp;
}
if (currentProp != null)
{
muscle.rigidbody.mass = currentProp.mass;
if (muscle.additionalPin != null)
{
muscle.additionalPinWeight = currentProp.additionalPinWeight;
muscle.additionalRigidbody.mass = currentProp.additionalPinMass;// * Mathf.Max(muscle.additionalPinWeight, currentProp.mass * 0.1f);
muscle.additionalRigidbody.drag = muscle.rigidbody.drag;
muscle.additionalRigidbody.angularDrag = muscle.rigidbody.angularDrag;
muscle.additionalRigidbody.useGravity = muscle.rigidbody.useGravity;
muscle.additionalRigidbody.inertiaTensor = Vector3.one * 0.00001f;
//muscle.additionalRigidbody.ResetInertiaTensor();
Vector3 f = additionalPinOffset + currentProp.additionalPinOffsetAdd;
if (lastAdditionalPinOffset != f)
{
muscle.additionalPinTarget.localPosition = f;
muscle.additionalPin.connectedAnchor = f;
lastAdditionalPinOffset = f;
}
}
}
}
void OnDrawGizmosSelected()
{
if (Application.isPlaying) return;
if (muscle.target == null) return;
//muscle.target.gameObject.hideFlags = HideFlags.None;
muscle.target.position = transform.position;
muscle.target.rotation = transform.rotation;
if (muscle.additionalPin != null && muscle.additionalPinTarget != null)
{
//muscle.additionalPin.gameObject.hideFlags = HideFlags.None;
//muscle.additionalPinTarget.gameObject.hideFlags = HideFlags.None;
muscle.additionalPin.transform.localPosition = additionalPinOffset;
muscle.additionalPin.transform.localRotation = Quaternion.identity;
muscle.additionalPinTarget.position = muscle.additionalPin.transform.position;
muscle.additionalPinTarget.rotation = muscle.additionalPin.transform.rotation;
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More