You can load LiveStage and LiveSheet now

This commit is contained in:
左右看
2022-09-04 09:59:21 +08:00
parent d7252c0db7
commit 10e3f51669
1039 changed files with 6166 additions and 34 deletions
@@ -0,0 +1,438 @@
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;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 01860b3861b7c4464b52da90d288bfea
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,227 @@
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;
}
}
}
@@ -0,0 +1,15 @@
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:
@@ -0,0 +1,833 @@
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();
}
}
}
}
}
}
@@ -0,0 +1,15 @@
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:
@@ -0,0 +1,118 @@
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);
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dfbba8c5a98ca4de682ccf628687b20c
timeCreated: 1438863362
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,157 @@
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;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c8748f43422c345aa87a97dd3e85819e
timeCreated: 1438864141
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
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;
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7d5fdd3d0ce82440097da4ed39d5dc5d
timeCreated: 1438863597
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,258 @@
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);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6b749367930f7464eba4d8cad81f261d
timeCreated: 1438866601
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,76 @@
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.
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 762171135dedc40ee90c4c961e36f9a0
timeCreated: 1435605962
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: ffb8680e3e6324a658749c533a23f6d1
folderAsset: yes
timeCreated: 1429874947
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,126 @@
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;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6de31dba92eea4c2492989c03b792b73
timeCreated: 1482328947
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
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);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a3b383b7d9ca6498692219a366e82ab7
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,222 @@
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;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0763c4b89286d49acaa9fdf15769756f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: