You can load LiveStage and LiveSheet now
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
public class AnimationBlocker : MonoBehaviour {
|
||||
|
||||
void LateUpdate()
|
||||
{
|
||||
transform.localPosition = Vector3.zero;
|
||||
transform.localRotation = Quaternion.identity;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e3269be4feb4a4269944c7ee3b1e8a03
|
||||
timeCreated: 1471635392
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,9 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 76c75a8f1e2844d2bbd3bd4bb15ed08c
|
||||
folderAsset: yes
|
||||
timeCreated: 1429874947
|
||||
licenseType: Store
|
||||
DefaultImporter:
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+12
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7d5fdd3d0ce82440097da4ed39d5dc5d
|
||||
timeCreated: 1438863597
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+258
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -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:
|
||||
+126
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6de31dba92eea4c2492989c03b792b73
|
||||
timeCreated: 1482328947
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
+33
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a3b383b7d9ca6498692219a366e82ab7
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
+222
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 0763c4b89286d49acaa9fdf15769756f
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,87 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 18beedbb70631428ba7cf3532df5cc35
|
||||
timeCreated: 1438861024
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,23 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
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
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 36692d5cb45554f5997a72cd4e2c92c8
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,125 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 373554a5ccbba4f58a126a7bb3910c82
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,276 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8f746daf167df400c968e119d42a30a5
|
||||
timeCreated: 1470733461
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,79 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 71460163d1998435b923a037e2f52ee9
|
||||
timeCreated: 1470245983
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,204 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6a611779f964f43249e427f512484a80
|
||||
timeCreated: 1431502619
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,248 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 024dd9da29038b948b4cdb292387d94b
|
||||
timeCreated: 1550491772
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,125 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
/// <summary>
|
||||
/// A point in the character's bone hierarchy for connecting props to.
|
||||
/// </summary>
|
||||
[HelpURL("http://root-motion.com/puppetmasterdox/html/page6.html")]
|
||||
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Prop Root")]
|
||||
public class PropRoot : MonoBehaviour {
|
||||
|
||||
// Open the User Manual URL
|
||||
[ContextMenu("User Manual")]
|
||||
void OpenUserManual() {
|
||||
Application.OpenURL("http://root-motion.com/puppetmasterdox/html/page6.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_prop_root.html");
|
||||
}
|
||||
|
||||
[Tooltip("Reference to the PuppetMaster component.")]
|
||||
/// <summary>
|
||||
/// Reference to the PuppetMaster component.
|
||||
/// </summary>
|
||||
public PuppetMaster puppetMaster;
|
||||
|
||||
[Tooltip("If a prop is connected, what will it's joint be connected to?")]
|
||||
/// <summary>
|
||||
/// If a prop is connected, what will it's joint be connected to?
|
||||
/// </summary>
|
||||
public Rigidbody connectTo;
|
||||
|
||||
[Tooltip("Is there a Prop connected to this PropRoot? Simply assign this value to connect, replace or drop props.")]
|
||||
/// <summary>
|
||||
/// Is there a Prop connected to this PropRoot? Simply assign this value to connect, replace or drop props.
|
||||
/// </summary>
|
||||
public Prop currentProp;
|
||||
|
||||
/// <summary>
|
||||
/// Dropping/Picking up normally works in the fixed update cycle where joints can be properly connected. Use this to drop a prop immediatelly.
|
||||
/// </summary>
|
||||
public void DropImmediate() {
|
||||
if (lastProp == null) return;
|
||||
puppetMaster.RemoveMuscleRecursive(lastProp.muscle, true, false, MuscleRemoveMode.Sever);
|
||||
lastProp.Drop();
|
||||
|
||||
currentProp = null;
|
||||
lastProp = null;
|
||||
}
|
||||
|
||||
private Prop lastProp;
|
||||
private bool fixedUpdateCalled;
|
||||
|
||||
void Awake() {
|
||||
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 currentProp has been assigned, it will be picked up AS IS, presuming it is already linked with the joints and held in the right position.
|
||||
// To pick up the prop from ground, assign it after Awake, for example in Start.
|
||||
if (currentProp != null) currentProp.StartPickedUp(this);
|
||||
}
|
||||
|
||||
void Update() {
|
||||
if (!fixedUpdateCalled) return;
|
||||
|
||||
// If dropped by another script or PuppetMaster behaviour
|
||||
if (currentProp != null && lastProp == currentProp && currentProp.muscle.connectedBody == null) {
|
||||
currentProp.Drop();
|
||||
currentProp = null;
|
||||
lastProp = null;
|
||||
}
|
||||
}
|
||||
|
||||
void FixedUpdate() {
|
||||
fixedUpdateCalled = true;
|
||||
|
||||
if (currentProp == lastProp) return;
|
||||
if (currentProp != null && !currentProp.initiated) return;
|
||||
|
||||
// Dropping current prop
|
||||
if (currentProp == null) {
|
||||
puppetMaster.RemoveMuscleRecursive(lastProp.muscle, true, false, MuscleRemoveMode.Sever);
|
||||
lastProp.Drop();
|
||||
}
|
||||
|
||||
// Picking up to an empty slot
|
||||
if (lastProp == null) {
|
||||
AttachProp(currentProp);
|
||||
}
|
||||
|
||||
// Switching props
|
||||
if (lastProp != null && currentProp != null) {
|
||||
puppetMaster.RemoveMuscleRecursive(lastProp.muscle, true, false, MuscleRemoveMode.Sever);
|
||||
AttachProp(currentProp);
|
||||
}
|
||||
|
||||
lastProp = currentProp;
|
||||
}
|
||||
|
||||
private void AttachProp(Prop prop) {
|
||||
prop.transform.position = transform.position;
|
||||
prop.transform.rotation = transform.rotation;
|
||||
|
||||
prop.PickUp(this);
|
||||
|
||||
/*
|
||||
prop.muscleProps.internalCollisionIgnores.muscles = new ConfigurableJoint[prop.internalCollisionIgnores.Length];
|
||||
for (int i = 0; i < prop.internalCollisionIgnores.Length; i++)
|
||||
{
|
||||
prop.muscleProps.internalCollisionIgnores.muscles[i] = puppetMaster.GetMuscle(puppetMaster.targetAnimator.GetBoneTransform(prop.internalCollisionIgnores[i])).joint;
|
||||
}
|
||||
*/
|
||||
|
||||
puppetMaster.AddMuscle(prop.muscle, prop.transform, connectTo, transform, prop.muscleProps, false, prop.forceLayers);
|
||||
|
||||
if (prop.additionalPin != null && prop.additionalPinTarget != null) {
|
||||
puppetMaster.AddMuscle(prop.additionalPin, prop.additionalPinTarget, prop.muscle.GetComponent<Rigidbody>(), prop.transform, new Muscle.Props(prop.additionalPinWeight, 0f, 0f, 0f, false, Muscle.Group.Prop), true, prop.forceLayers);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8ce8c6ececc4043119b246f80bb45d82
|
||||
timeCreated: 1431603994
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,23 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// The default prop template with no functionality
|
||||
[HelpURL("http://root-motion.com/puppetmasterdox/html/page6.html")]
|
||||
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/Prop Template")]
|
||||
public class PropTemplate: Prop {
|
||||
|
||||
protected override void OnStart() {
|
||||
// Initiate stuff here.
|
||||
}
|
||||
|
||||
protected override void OnPickUp(PropRoot propRoot) {
|
||||
// Called when the prop has been picked up and connected to a PropRoot.
|
||||
}
|
||||
|
||||
protected override void OnDrop() {
|
||||
// Called when the prop has been dropped.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b984b099bfed34787ac86d63311f278e
|
||||
timeCreated: 1435737903
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 1c86ba130e5a5458a98e3b482192a6dd
|
||||
labels:
|
||||
- Ragdoll
|
||||
- Physics
|
||||
- Activeragdolls
|
||||
timeCreated: 1444739157
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 10100
|
||||
icon: {fileID: 2800000, guid: 8894e7b9cd0dd9a4b945ffc044647939, type: 3}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,846 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
[System.Serializable]
|
||||
public enum MuscleRemoveMode {
|
||||
Sever, // Severs the body part disconnecting the first joit
|
||||
Explode, // Explodes the body part disconnecting all joints
|
||||
Numb, // Removes the muscles, keeps the joints connected, but disables spring and damper forces
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public enum MuscleDisconnectMode
|
||||
{
|
||||
Sever,
|
||||
Explode
|
||||
}
|
||||
|
||||
// Contains high level API calls for changing the PuppetMaster's muscle structure.
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
#region Public API
|
||||
|
||||
/// <summary>
|
||||
/// Adds a PropMuscle to the puppet at runtime. If Vector3.zero passed for additionalPinOffset, additional pin will not be added.
|
||||
/// </summary>
|
||||
public bool AddPropMuscle(ConfigurableJoint addPropMuscleTo, Vector3 position, Quaternion rotation, Vector3 additionalPinOffset, Transform targetParent = null, PuppetMasterProp initiateWithProp = null)
|
||||
{
|
||||
if (!initiated)
|
||||
{
|
||||
Debug.LogError("Can not add Prop Muscle to PuppetMaster that has not been initiated! Please use Start() instead of Awake() or PuppetMaster.OnPostInitiate delegate to call AddPropMuscle.", transform);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (addPropMuscleTo != null)
|
||||
{
|
||||
bool isFlat = HierarchyIsFlat();
|
||||
|
||||
var addToMuscle = GetMuscle(addPropMuscleTo);
|
||||
if (addToMuscle != null)
|
||||
{
|
||||
GameObject go = new GameObject("Prop Muscle " + addPropMuscleTo.name);
|
||||
go.layer = addPropMuscleTo.gameObject.layer;
|
||||
go.transform.parent = isFlat ? transform : addPropMuscleTo.transform;
|
||||
go.transform.position = position;
|
||||
go.transform.rotation = rotation;
|
||||
|
||||
go.AddComponent<Rigidbody>();
|
||||
|
||||
GameObject target = new GameObject("Prop Muscle Target " + addPropMuscleTo.name);
|
||||
target.gameObject.layer = addToMuscle.target.gameObject.layer;
|
||||
target.transform.parent = targetParent != null? targetParent: addToMuscle.target;
|
||||
target.transform.position = go.transform.position;
|
||||
target.transform.rotation = go.transform.rotation;
|
||||
|
||||
ConfigurableJoint joint = go.AddComponent<ConfigurableJoint>();
|
||||
joint.xMotion = ConfigurableJointMotion.Locked;
|
||||
joint.yMotion = ConfigurableJointMotion.Locked;
|
||||
joint.zMotion = ConfigurableJointMotion.Locked;
|
||||
joint.angularXMotion = ConfigurableJointMotion.Locked;
|
||||
joint.angularYMotion = ConfigurableJointMotion.Locked;
|
||||
joint.angularZMotion = ConfigurableJointMotion.Locked;
|
||||
|
||||
Muscle.Props props = new Muscle.Props();
|
||||
props.group = Muscle.Group.Prop;
|
||||
|
||||
AddMuscle(joint, target.transform, addPropMuscleTo.GetComponent<Rigidbody>(), targetParent != null ? targetParent : addToMuscle.target, props, false, true);
|
||||
|
||||
muscles[muscles.Length - 1].isPropMuscle = true;
|
||||
|
||||
var propMuscle = go.AddComponent<PropMuscle>();
|
||||
propMuscle.puppetMaster = this;
|
||||
propMuscle.additionalPinOffset = additionalPinOffset;
|
||||
propMuscle.currentProp = initiateWithProp;
|
||||
if (additionalPinOffset != Vector3.zero) propMuscle.AddAdditionalPin();
|
||||
|
||||
Array.Resize(ref propMuscles, propMuscles.Length + 1);
|
||||
propMuscles[propMuscles.Length - 1] = propMuscle;
|
||||
propMuscle.OnInitiate();
|
||||
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Can't add Prop Muscle to a ConfigurableJoint that is not in the list of PuppetMaster.muscles.", transform);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError("Please assign the ConfigurableJoint of the muscle you wish to add the Prop Muscle to.", transform);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is the muscle scheduled for disconnecting?
|
||||
/// </summary>
|
||||
public bool IsDisconnecting(int muscleIndex)
|
||||
{
|
||||
return disconnectMuscleFlags[muscleIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is the muscle scheduled for reconnecting
|
||||
/// </summary>
|
||||
public bool IsReconnecting(int muscleIndex)
|
||||
{
|
||||
return reconnectMuscleFlags[muscleIndex];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disconnects muscle from index. In Sever mode, the muscle and it's children will be disconnected in one piece (cutting limb off). In Explode mode the muscle and all it's children will be cut off. If Deactivate is true, the disconnected muscle GameObjects will be deactivated.
|
||||
/// </summary>
|
||||
public void DisconnectMuscleRecursive(int index, MuscleDisconnectMode disconnectMode = MuscleDisconnectMode.Sever, bool deactivate = false)
|
||||
{
|
||||
if (index < 0 || index >= muscles.Length)
|
||||
{
|
||||
Debug.LogError("PuppetMaster.DisconnectMuscleRecursive() called with out of range index: " + index, transform);
|
||||
return;
|
||||
}
|
||||
|
||||
disconnectMuscleFlags[index] = true;
|
||||
muscleDisconnectModes[index] = disconnectMode;
|
||||
disconnectDeactivateFlags[index] = deactivate;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconnects all muscles starting from the specified index.
|
||||
/// </summary>
|
||||
public void ReconnectMuscleRecursive(int index)
|
||||
{
|
||||
if (index < 0 || index >= muscles.Length)
|
||||
{
|
||||
Debug.LogError("PuppetMaster.ReconnectMuscleRecursive() called with out of range index: " + index, transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (index > 0) index = GetHighestDisconnectedParentIndex(index);
|
||||
|
||||
reconnectMuscleFlags[index] = true;
|
||||
|
||||
// Disable reconnecting muscles, so they could be reset on actual reconnect
|
||||
if (muscles[index].state.resetFlag) muscles[index].joint.gameObject.SetActive(false);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
int childIndex = muscles[index].childIndexes[i];
|
||||
if (muscles[childIndex].state.resetFlag) muscles[childIndex].joint.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NB! Make sure to call this from FixedUpdate!
|
||||
/// Creates a new muscle for the specified "joint" and targets it to the "target". The joint will be connected to the specified "connectTo" Muscle.
|
||||
/// Note that the joint will be binded to it's current position and rotation relative to the "connectTo", so make sure the added object is positioned correctly when calling this.
|
||||
/// This method allocates memory, avoid using it each frame.
|
||||
/// </summary>
|
||||
public void AddMuscle(ConfigurableJoint joint, Transform target, Rigidbody connectTo, Transform targetParent, Muscle.Props muscleProps = null, bool forceTreeHierarchy = false, bool forceLayers = true) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
if (!initiated) {
|
||||
Debug.LogWarning("PuppetMaster has not been initiated.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ContainsJoint(joint)) {
|
||||
Debug.LogWarning("Joint " + joint.name + " is already used by a Muscle", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (target == null) {
|
||||
Debug.LogWarning("AddMuscle was called with a null 'target' reference.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectTo == joint.GetComponent<Rigidbody>()) {
|
||||
Debug.LogWarning("ConnectTo is the joint's own Rigidbody, can not add muscle.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeMode == Mode.Disabled) {
|
||||
Debug.LogWarning("Adding muscles to disabled PuppetMasters is not currently supported.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (muscleProps == null) muscleProps = new Muscle.Props();
|
||||
|
||||
Muscle muscle = new Muscle();
|
||||
muscle.props = muscleProps;
|
||||
muscle.joint = joint;
|
||||
muscle.target = target;
|
||||
muscle.joint.transform.parent = (hierarchyIsFlat || connectTo == null) && !forceTreeHierarchy? transform: connectTo.transform;
|
||||
|
||||
var animationBlocker = target.GetComponent<AnimationBlocker>();
|
||||
if (animationBlocker != null) Destroy(animationBlocker);
|
||||
|
||||
if (forceLayers) {
|
||||
joint.gameObject.layer = gameObject.layer; //@todo what if collider is on a child gameobject?
|
||||
target.gameObject.layer = targetRoot.gameObject.layer;
|
||||
}
|
||||
|
||||
if (connectTo != null) {
|
||||
muscle.target.parent = targetParent;
|
||||
|
||||
Vector3 relativePosition = GetMuscle(connectTo).transform.InverseTransformPoint(muscle.target.position);
|
||||
Quaternion relativeRotation = Quaternion.Inverse(GetMuscle(connectTo).transform.rotation) * muscle.target.rotation;
|
||||
|
||||
joint.transform.position = connectTo.transform.TransformPoint(relativePosition);
|
||||
joint.transform.rotation = connectTo.transform.rotation * relativeRotation;
|
||||
|
||||
joint.connectedBody = connectTo;
|
||||
|
||||
joint.xMotion = ConfigurableJointMotion.Locked;
|
||||
joint.yMotion = ConfigurableJointMotion.Locked;
|
||||
joint.zMotion = ConfigurableJointMotion.Locked;
|
||||
}
|
||||
|
||||
muscle.Initiate(muscles);
|
||||
|
||||
if (connectTo != null) {
|
||||
muscle.rigidbody.velocity = connectTo.velocity;
|
||||
muscle.rigidbody.angularVelocity = connectTo.angularVelocity;
|
||||
}
|
||||
|
||||
// Ignore internal collisions
|
||||
if (!internalCollisions) {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
muscle.IgnoreInternalCollisions(muscles[i]);
|
||||
}
|
||||
}
|
||||
|
||||
Array.Resize(ref muscles, muscles.Length + 1);
|
||||
muscles[muscles.Length - 1] = muscle;
|
||||
muscle.index = muscles.Length - 1;
|
||||
|
||||
// Update angular limit ignoring
|
||||
muscle.IgnoreAngularLimits(!angularLimits);
|
||||
|
||||
if (behaviours.Length > 0) {
|
||||
muscle.broadcaster = muscle.joint.gameObject.AddComponent<MuscleCollisionBroadcaster>();
|
||||
muscle.broadcaster.puppetMaster = this;
|
||||
muscle.broadcaster.muscleIndex = muscles.Length - 1;
|
||||
}
|
||||
|
||||
muscle.jointBreakBroadcaster = muscle.joint.gameObject.AddComponent<JointBreakBroadcaster>();
|
||||
muscle.jointBreakBroadcaster.puppetMaster = this;
|
||||
muscle.jointBreakBroadcaster.muscleIndex = muscles.Length - 1;
|
||||
|
||||
UpdateHierarchies();
|
||||
CheckMassVariation(100f, true);
|
||||
|
||||
foreach (BehaviourBase b in behaviours) b.OnMuscleAdded(muscle);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Complete rebuild of this puppet's muscle hierarchy to it's default state as it was at first initiation (required that none of the original components have been destroyed).
|
||||
/// </summary>
|
||||
public void Rebuild() {
|
||||
rebuildFlag = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the muscle with the specified joint and all muscles connected to it from PuppetMaster management. This will not destroy the body part/prop, but just release it from following the target.
|
||||
/// If you call RemoveMuscleRecursive on an upper arm muscle, the entire arm will be disconnected from the rest of the body.
|
||||
/// </summary>
|
||||
/// <param name="joint">The joint of the muscle (and the muscles connected to it) to remove.</param>
|
||||
/// <param name="attachTarget">If set to <c>true</c> , the target Transform of the first muscle will be parented to the disconnected limb.</param>
|
||||
/// <param name="blockTargetAnimation">If set to <c>true</c>, will add AnimationBlocker.cs to the removed target bones. That will override animation that would otherwise still be writing on those bones.</param>
|
||||
/// <param name="removeMode">Remove mode. Sever cuts the body part by disconnecting the first joint. Explode explodes the body part disconnecting all joints. Numb removes the muscles from PuppetMaster management, keeps the joints connected and disables spring and damper forces.</param>
|
||||
public void RemoveMuscleRecursive(ConfigurableJoint joint, bool attachTarget, bool blockTargetAnimation = false, MuscleRemoveMode removeMode = MuscleRemoveMode.Sever)
|
||||
{
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
if (joint == null)
|
||||
{
|
||||
Debug.LogWarning("RemoveMuscleRecursive was called with a null 'joint' reference.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ContainsJoint(joint))
|
||||
{
|
||||
Debug.LogWarning("No Muscle with the specified joint was found, can not remove muscle.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
int index = GetMuscleIndex(joint);
|
||||
Muscle[] newMuscles = new Muscle[muscles.Length - (muscles[index].childIndexes.Length + 1)];
|
||||
|
||||
int added = 0;
|
||||
for (int i = 0; i < muscles.Length; i++)
|
||||
{
|
||||
if (i != index && !muscles[index].childFlags[i])
|
||||
{
|
||||
newMuscles[added] = muscles[i];
|
||||
added++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (muscles[i].broadcaster != null)
|
||||
{
|
||||
muscles[i].broadcaster.enabled = false;
|
||||
Destroy(muscles[i].broadcaster);
|
||||
}
|
||||
if (muscles[i].jointBreakBroadcaster != null)
|
||||
{
|
||||
muscles[i].jointBreakBroadcaster.enabled = false;
|
||||
Destroy(muscles[i].jointBreakBroadcaster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch (removeMode)
|
||||
{
|
||||
case MuscleRemoveMode.Sever:
|
||||
DisconnectJoint(muscles[index].joint);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
KillJoint(muscles[muscles[index].childIndexes[i]].joint);
|
||||
}
|
||||
break;
|
||||
case MuscleRemoveMode.Explode:
|
||||
DisconnectJoint(muscles[index].joint);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
DisconnectJoint(muscles[muscles[index].childIndexes[i]].joint);
|
||||
}
|
||||
break;
|
||||
case MuscleRemoveMode.Numb:
|
||||
KillJoint(muscles[index].joint);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
KillJoint(muscles[muscles[index].childIndexes[i]].joint);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
muscles[index].transform.parent = null;
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
if (removeMode == MuscleRemoveMode.Explode || muscles[muscles[index].childIndexes[i]].transform.parent == transform)
|
||||
{
|
||||
muscles[muscles[index].childIndexes[i]].transform.parent = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
foreach (BehaviourBase b in behaviours)
|
||||
{
|
||||
b.OnMuscleRemoved(muscles[index]);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
var c = muscles[muscles[index].childIndexes[i]];
|
||||
b.OnMuscleRemoved(c);
|
||||
}
|
||||
}
|
||||
|
||||
if (attachTarget)
|
||||
{
|
||||
muscles[index].target.parent = muscles[index].transform;
|
||||
muscles[index].target.position = muscles[index].transform.position;
|
||||
muscles[index].target.rotation = muscles[index].transform.rotation * muscles[index].targetRotationRelative;
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
var c = muscles[muscles[index].childIndexes[i]];
|
||||
c.target.parent = c.transform;
|
||||
c.target.position = c.transform.position;
|
||||
c.target.rotation = c.transform.rotation;
|
||||
}
|
||||
}
|
||||
|
||||
if (blockTargetAnimation)
|
||||
{
|
||||
var blocker = muscles[index].target.gameObject.GetComponent<AnimationBlocker>();
|
||||
if (blocker == null) blocker = muscles[index].target.gameObject.AddComponent<AnimationBlocker>();
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
var c = muscles[muscles[index].childIndexes[i]];
|
||||
|
||||
blocker = c.target.gameObject.GetComponent<AnimationBlocker>();
|
||||
if (blocker == null) blocker = c.target.gameObject.AddComponent<AnimationBlocker>();
|
||||
}
|
||||
}
|
||||
|
||||
if (OnMuscleRemoved != null) OnMuscleRemoved(muscles[index]);
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
var c = muscles[muscles[index].childIndexes[i]];
|
||||
if (OnMuscleRemoved != null) OnMuscleRemoved(c);
|
||||
}
|
||||
|
||||
// Enable collisions between the new muscles and the removed colliders
|
||||
if (!internalCollisionsEnabled)
|
||||
{
|
||||
foreach (Muscle newMuscle in newMuscles)
|
||||
{
|
||||
newMuscle.ResetInternalCollisions(muscles[index], false);
|
||||
|
||||
for (int childMuscleIndex = 0; childMuscleIndex < muscles[index].childIndexes.Length; childMuscleIndex++)
|
||||
{
|
||||
newMuscle.ResetInternalCollisions(muscles[childMuscleIndex], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
muscles = newMuscles;
|
||||
|
||||
UpdateHierarchies();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NB! Make sure to call this from FixedUpdate!
|
||||
/// Replaces a muscle with a new one. This can be used to replace props,
|
||||
/// but in most cases it would be faster and more efficient to do it by maintaining the muscle (the Joint and the Rigidbody) and just replacing the colliders and the graphical model.
|
||||
/// This method allocates memory, avoid using it each frame.
|
||||
/// </summary>
|
||||
public void ReplaceMuscle(ConfigurableJoint oldJoint, ConfigurableJoint newJoint) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
// @todo
|
||||
Debug.LogWarning("@todo", transform);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NB! Make sure to call this from FixedUpdate!
|
||||
/// Completely replaces the muscle structure. Make sure the new muscle objects are positioned and rotated correctly relative to their targets.
|
||||
/// This method allocates memory, avoid using it each frame.
|
||||
/// </summary>
|
||||
public void SetMuscles(Muscle[] newMuscles) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
// @todo
|
||||
Debug.LogWarning("@todo", transform);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Disables the muscle with the specified joint and all muscles connected to it. This is a faster and more efficient alternative to RemoveMuscleRecursive,
|
||||
/// as it will not require reinitiating the muscles.
|
||||
/// </summary>
|
||||
public void DisableMuscleRecursive(ConfigurableJoint joint) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
// @todo
|
||||
Debug.LogWarning("@todo", transform);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-enables a previously disabled muscle and the muscles connected to it.
|
||||
/// </summary>
|
||||
public void EnableMuscleRecursive(ConfigurableJoint joint) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
// @todo
|
||||
Debug.LogWarning("@todo", transform);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Flattens the ragdoll hierarchy so that all muscles are parented to the PuppetMaster.
|
||||
/// </summary>
|
||||
[ContextMenu("Flatten Muscle Hierarchy")]
|
||||
public void FlattenHierarchy() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.joint != null) m.joint.transform.parent = transform;
|
||||
}
|
||||
|
||||
hierarchyIsFlat = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a hierarchy tree from the muscles.
|
||||
/// </summary>
|
||||
[ContextMenu("Tree Muscle Hierarchy")]
|
||||
public void TreeHierarchy() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.joint != null) {
|
||||
m.joint.transform.parent = m.joint.connectedBody != null? m.joint.connectedBody.transform: transform;
|
||||
}
|
||||
}
|
||||
|
||||
hierarchyIsFlat = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves all muscles to the positions of their targets.
|
||||
/// </summary>
|
||||
[ContextMenu("Fix Muscle Positions")]
|
||||
public void FixMusclePositions() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.joint != null && m.target != null) {
|
||||
m.joint.transform.position = m.target.position;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves all muscles to the positions and rotations of their targets.
|
||||
/// </summary>
|
||||
[ContextMenu("Fix Muscle Positions and Rotations")]
|
||||
public void FixMusclePositionsAndRotations()
|
||||
{
|
||||
foreach (Muscle m in muscles)
|
||||
{
|
||||
if (m.joint != null && m.target != null)
|
||||
{
|
||||
m.joint.transform.position = m.target.position;
|
||||
m.joint.transform.rotation = m.target.rotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Are all the muscles parented to the PuppetMaster Transform?
|
||||
/// </summary>
|
||||
public bool HierarchyIsFlat()
|
||||
{
|
||||
foreach (Muscle m in muscles)
|
||||
{
|
||||
if (m.joint.transform.parent != transform) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion Public API
|
||||
|
||||
private int GetHighestDisconnectedParentIndex(int index)
|
||||
{
|
||||
for (int i = muscles[index].parentIndexes.Length - 1; i > -1; i--)
|
||||
{
|
||||
int parentIndex = muscles[index].parentIndexes[i];
|
||||
if (muscles[parentIndex].state.isDisconnected) return parentIndex;
|
||||
}
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
private void ProcessDisconnects()
|
||||
{
|
||||
for (int i = 0; i < disconnectMuscleFlags.Length; i++)
|
||||
{
|
||||
if (disconnectMuscleFlags[i]) OnDisconnectMuscleRecursive(i, muscleDisconnectModes[i], disconnectDeactivateFlags[i]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < disconnectMuscleFlags.Length; i++)
|
||||
{
|
||||
disconnectMuscleFlags[i] = false;
|
||||
disconnectDeactivateFlags[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessReconnects()
|
||||
{
|
||||
for (int i = 0; i < reconnectMuscleFlags.Length; i++)
|
||||
{
|
||||
if (reconnectMuscleFlags[i]) OnReconnectMuscleRecursive(i);
|
||||
}
|
||||
|
||||
for (int i = 0; i < reconnectMuscleFlags.Length; i++)
|
||||
{
|
||||
reconnectMuscleFlags[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDisconnectMuscleRecursive(int index, MuscleDisconnectMode disconnectMode = MuscleDisconnectMode.Sever, bool deactivate = false)
|
||||
{
|
||||
// Reset flags
|
||||
if (!muscles[index].joint.gameObject.activeInHierarchy || deactivate) muscles[index].state.resetFlag = true;
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
int childIndex = muscles[index].childIndexes[i];
|
||||
if (!muscles[childIndex].joint.gameObject.activeInHierarchy || deactivate) muscles[childIndex].state.resetFlag = true;
|
||||
}
|
||||
|
||||
// Disconnect individual muscles
|
||||
DisconnectMuscle(muscles[index], true, deactivate);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
int childIndex = muscles[index].childIndexes[i];
|
||||
bool alreadyDone = disconnectMode == MuscleDisconnectMode.Sever && muscles[childIndex].state.isDisconnected;
|
||||
if (disconnectMode == MuscleDisconnectMode.Explode && muscles[childIndex].joint.xMotion != ConfigurableJointMotion.Free) alreadyDone = false;
|
||||
|
||||
if (!alreadyDone)
|
||||
{
|
||||
DisconnectMuscle(muscles[childIndex], disconnectMode == MuscleDisconnectMode.Explode, deactivate);
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect the last muscle too if all others removed
|
||||
if (!muscles[0].state.isDisconnected)
|
||||
{
|
||||
bool lastMuscle = true;
|
||||
|
||||
for (int i = 1; i < muscles.Length; i++)
|
||||
{
|
||||
if (!muscles[i].state.isDisconnected)
|
||||
{
|
||||
lastMuscle = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (lastMuscle)
|
||||
{
|
||||
DisconnectMuscleRecursive(0, MuscleDisconnectMode.Sever);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void DisconnectMuscle(Muscle m, bool sever, bool deactivate)
|
||||
{
|
||||
m.state.pinWeightMlp = 0f;
|
||||
m.state.muscleWeightMlp = 0f;
|
||||
m.state.muscleDamperAdd = 0f;
|
||||
m.state.muscleDamperMlp = 0f;
|
||||
m.state.mappingWeightMlp = 0f;
|
||||
m.state.maxForceMlp = 0f;
|
||||
m.state.immunity = 0f;
|
||||
m.state.impulseMlp = 1f;
|
||||
|
||||
if (sever)
|
||||
{
|
||||
m.joint.xMotion = ConfigurableJointMotion.Free;
|
||||
m.joint.yMotion = ConfigurableJointMotion.Free;
|
||||
m.joint.zMotion = ConfigurableJointMotion.Free;
|
||||
|
||||
m.IgnoreAngularLimits(true);
|
||||
|
||||
if (!hierarchyIsFlat)
|
||||
{
|
||||
m.joint.transform.parent = transform;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m.IgnoreAngularLimits(false);
|
||||
}
|
||||
|
||||
bool applyMappedVelocity = !m.joint.gameObject.activeInHierarchy || m.rigidbody.isKinematic;
|
||||
if (activeState == State.Frozen) applyMappedVelocity = false;
|
||||
|
||||
// In case disconnecting in disabled mode
|
||||
if (!m.joint.gameObject.activeInHierarchy && !deactivate)
|
||||
{
|
||||
m.MoveToTarget();
|
||||
m.joint.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
m.SetKinematic(false);
|
||||
JointDrive slerpDrive = new JointDrive();
|
||||
slerpDrive.positionSpring = 0f;
|
||||
slerpDrive.maximumForce = 0f;
|
||||
slerpDrive.positionDamper = 0f;
|
||||
m.joint.slerpDrive = slerpDrive;
|
||||
|
||||
// Enable internal collisions with the disconnected muscle
|
||||
if (!deactivate)
|
||||
{
|
||||
for (int i = 0; i < muscles.Length; i++)
|
||||
{
|
||||
if (muscles[i] != m && !muscles[i].state.isDisconnected)
|
||||
{
|
||||
foreach (Collider c1 in m.colliders)
|
||||
{
|
||||
foreach (Collider c2 in muscles[i].colliders)
|
||||
{
|
||||
if (c1.enabled && c2.enabled) Physics.IgnoreCollision(c1, c2, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (applyMappedVelocity)
|
||||
{
|
||||
m.rigidbody.velocity = m.mappedVelocity;
|
||||
m.rigidbody.angularVelocity = m.mappedAngularVelocity;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
m.joint.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
if (m.isPropMuscle)
|
||||
{
|
||||
var propMuscle = m.joint.GetComponent<PropMuscle>();
|
||||
if (propMuscle.activeProp != null) propMuscle.currentProp = null;
|
||||
}
|
||||
|
||||
m.state.isDisconnected = true;
|
||||
|
||||
foreach (BehaviourBase b in behaviours) b.OnMuscleDisconnected(m);
|
||||
if (OnMuscleDisconnected != null) OnMuscleDisconnected(m);
|
||||
}
|
||||
|
||||
private void OnReconnectMuscleRecursive(int index)
|
||||
{
|
||||
// Special case for reconnecting the entire puppet
|
||||
if (index == 0)
|
||||
{
|
||||
state = State.Alive;
|
||||
|
||||
foreach (Muscle m in muscles)
|
||||
{
|
||||
m.state.isDisconnected = false;
|
||||
m.FixTargetTransforms();
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles)
|
||||
{
|
||||
m.Reset();
|
||||
m.Read();
|
||||
m.ClearVelocities();
|
||||
}
|
||||
}
|
||||
|
||||
ReconnectMuscle(muscles[index]);
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++)
|
||||
{
|
||||
int childIndex = muscles[index].childIndexes[i];
|
||||
ReconnectMuscle(muscles[childIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReconnectMuscle(Muscle m)
|
||||
{
|
||||
m.state.isDisconnected = false;
|
||||
|
||||
if (activeState != State.Frozen && !m.isPropMuscle)
|
||||
{
|
||||
m.target.position = m.targetAnimatedPosition;
|
||||
m.target.rotation = m.targetAnimatedWorldRotation;
|
||||
}
|
||||
|
||||
if (m != muscles[0])
|
||||
{
|
||||
m.joint.xMotion = ConfigurableJointMotion.Locked;
|
||||
m.joint.yMotion = ConfigurableJointMotion.Locked;
|
||||
m.joint.zMotion = ConfigurableJointMotion.Locked;
|
||||
|
||||
if (!hierarchyIsFlat && m.joint.connectedBody != null)
|
||||
{
|
||||
m.transform.parent = m.joint.connectedBody.transform;
|
||||
}
|
||||
}
|
||||
|
||||
bool disable = false;
|
||||
if (m.joint.connectedBody != null && !m.joint.connectedBody.gameObject.activeInHierarchy) disable = true;
|
||||
if (m.joint.connectedBody == null)
|
||||
{
|
||||
if (activeMode == Mode.Disabled || activeState == State.Frozen) disable = true;
|
||||
}
|
||||
|
||||
if (disable)
|
||||
{
|
||||
m.joint.gameObject.SetActive(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!m.joint.gameObject.activeInHierarchy || m.state.resetFlag)
|
||||
{
|
||||
m.Reset();
|
||||
m.joint.gameObject.SetActive(true);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (activeState != State.Frozen) m.MoveToTarget();
|
||||
}
|
||||
}
|
||||
|
||||
if (activeMode == Mode.Kinematic) m.SetKinematic(true);
|
||||
|
||||
if (activeState == State.Dead)
|
||||
{
|
||||
m.ResetTargetLocalPosition();
|
||||
m.SetMuscleRotation(muscleWeight * stateSettings.deadMuscleWeight, muscleSpring, muscleDamper + stateSettings.deadMuscleDamper);
|
||||
}
|
||||
|
||||
m.state.resetFlag = false;
|
||||
m.ClearVelocities();
|
||||
|
||||
m.state.pinWeightMlp = 1;
|
||||
m.state.muscleWeightMlp = 1;
|
||||
m.state.muscleDamperMlp = 1;
|
||||
m.state.maxForceMlp = 1;
|
||||
m.state.mappingWeightMlp = 1f;
|
||||
|
||||
UpdateInternalCollisions(m);
|
||||
m.IgnoreAngularLimits(!angularLimits);
|
||||
|
||||
foreach (BehaviourBase b in behaviours) b.OnMuscleReconnected(m);
|
||||
if (OnMuscleReconnected != null) OnMuscleReconnected(m);
|
||||
}
|
||||
|
||||
private void AddIndexesRecursive(int index, ref int[] indexes) {
|
||||
int l = indexes.Length;
|
||||
Array.Resize(ref indexes, indexes.Length + 1 + muscles[index].childIndexes.Length);
|
||||
indexes[l] = index;
|
||||
|
||||
if (muscles[index].childIndexes.Length == 0) return;
|
||||
|
||||
for (int i = 0; i < muscles[index].childIndexes.Length; i++) {
|
||||
AddIndexesRecursive(muscles[index].childIndexes[i], ref indexes);
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnects a joint without destroying it
|
||||
private void DisconnectJoint(ConfigurableJoint joint) {
|
||||
if (mode == Mode.Disabled) joint.gameObject.SetActive(true);
|
||||
|
||||
joint.connectedBody = null;
|
||||
|
||||
KillJoint(joint);
|
||||
|
||||
joint.xMotion = ConfigurableJointMotion.Free;
|
||||
joint.yMotion = ConfigurableJointMotion.Free;
|
||||
joint.zMotion = ConfigurableJointMotion.Free;
|
||||
joint.angularXMotion = ConfigurableJointMotion.Free;
|
||||
joint.angularYMotion = ConfigurableJointMotion.Free;
|
||||
joint.angularZMotion = ConfigurableJointMotion.Free;
|
||||
}
|
||||
|
||||
// Disables joint target rotation, position spring and damper
|
||||
private void KillJoint(ConfigurableJoint joint) {
|
||||
joint.targetRotation = Quaternion.identity;
|
||||
JointDrive j = new JointDrive();
|
||||
j.positionSpring = 0f;
|
||||
j.positionDamper = 0f;
|
||||
|
||||
#if UNITY_5_2
|
||||
j.mode = JointDriveMode.None;
|
||||
#endif
|
||||
|
||||
joint.slerpDrive = j;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: ab07c30315be74fa3a14dfc5773c61b5
|
||||
timeCreated: 1436431965
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,123 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics
|
||||
{
|
||||
|
||||
[CreateAssetMenu(fileName = "PuppetMaster Humanoid Config", menuName = "PuppetMaster/Humanoid Config", order = 1)]
|
||||
public class PuppetMasterHumanoidConfig : ScriptableObject
|
||||
{
|
||||
|
||||
[System.Serializable]
|
||||
public class HumanoidMuscle
|
||||
{
|
||||
[SerializeField] [HideInInspector] public string name;
|
||||
public HumanBodyBones bone;
|
||||
public Muscle.Props props;
|
||||
}
|
||||
|
||||
[LargeHeader("Simulation")]
|
||||
|
||||
public PuppetMaster.State state;
|
||||
public PuppetMaster.StateSettings stateSettings = PuppetMaster.StateSettings.Default;
|
||||
public PuppetMaster.Mode mode;
|
||||
public float blendTime = 0.1f;
|
||||
public bool fixTargetTransforms = true;
|
||||
public int solverIterationCount = 6;
|
||||
public bool visualizeTargetPose = true;
|
||||
|
||||
[LargeHeader("Master Weights")]
|
||||
|
||||
[Range(0f, 1f)] public float mappingWeight = 1f;
|
||||
[Range(0f, 1f)] public float pinWeight = 1f;
|
||||
[Range(0f, 1f)] public float muscleWeight = 1f;
|
||||
|
||||
[LargeHeader("Joint and Muscle Settings")]
|
||||
|
||||
public float muscleSpring = 100f;
|
||||
public float muscleDamper = 0f;
|
||||
[Range(1f, 8f)] public float pinPow = 4f;
|
||||
[Range(0f, 100f)] public float pinDistanceFalloff = 5;
|
||||
public bool angularPinning;
|
||||
public bool updateJointAnchors = true;
|
||||
public bool supportTranslationAnimation;
|
||||
public bool angularLimits;
|
||||
public bool internalCollisions;
|
||||
|
||||
[LargeHeader("Individual Muscle Settings")]
|
||||
|
||||
public HumanoidMuscle[] muscles = new HumanoidMuscle[0];
|
||||
|
||||
/// <summary>
|
||||
/// Applies this config to the specified PuppetMaster.
|
||||
/// </summary>
|
||||
/// <param name="p">P.</param>
|
||||
public void ApplyTo(PuppetMaster p)
|
||||
{
|
||||
if (p.targetRoot == null)
|
||||
{
|
||||
Debug.LogWarning("Please assign 'Target Root' for PuppetMaster using a Humanoid Config.", p.transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (p.targetAnimator == null)
|
||||
{
|
||||
Debug.LogError("PuppetMaster 'Target Root' does not have an Animator component. Can not use Humanoid Config.", p.transform);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!p.targetAnimator.isHuman)
|
||||
{
|
||||
Debug.LogError("PuppetMaster target is not a Humanoid. Can not use Humanoid Config.", p.transform);
|
||||
return;
|
||||
}
|
||||
|
||||
p.state = state;
|
||||
p.stateSettings = stateSettings;
|
||||
p.mode = mode;
|
||||
p.blendTime = blendTime;
|
||||
p.fixTargetTransforms = fixTargetTransforms;
|
||||
p.solverIterationCount = solverIterationCount;
|
||||
p.visualizeTargetPose = visualizeTargetPose;
|
||||
p.mappingWeight = mappingWeight;
|
||||
p.pinWeight = pinWeight;
|
||||
p.muscleWeight = muscleWeight;
|
||||
p.muscleSpring = muscleSpring;
|
||||
p.muscleDamper = muscleDamper;
|
||||
p.pinPow = pinPow;
|
||||
p.pinDistanceFalloff = pinDistanceFalloff;
|
||||
p.angularPinning = angularPinning;
|
||||
p.updateJointAnchors = updateJointAnchors;
|
||||
p.supportTranslationAnimation = supportTranslationAnimation;
|
||||
p.angularLimits = angularLimits;
|
||||
p.internalCollisions = internalCollisions;
|
||||
|
||||
foreach (HumanoidMuscle h in muscles)
|
||||
{
|
||||
var m = GetMuscle(h.bone, p.targetAnimator, p);
|
||||
if (m != null)
|
||||
{
|
||||
m.props.group = h.props.group;
|
||||
m.props.mappingWeight = h.props.mappingWeight;
|
||||
m.props.mapPosition = h.props.mapPosition;
|
||||
m.props.muscleDamper = h.props.muscleDamper;
|
||||
m.props.muscleWeight = h.props.muscleWeight;
|
||||
m.props.pinWeight = h.props.pinWeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Muscle GetMuscle(HumanBodyBones boneId, Animator animator, PuppetMaster puppetMaster)
|
||||
{
|
||||
Transform bone = animator.GetBoneTransform(boneId);
|
||||
if (bone == null) return null;
|
||||
|
||||
foreach (Muscle m in puppetMaster.muscles)
|
||||
{
|
||||
if (m.target == bone) return m;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f10d3d82c6eecfd4da1589ecec319d68
|
||||
timeCreated: 1485251545
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,263 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Switching and blending between Modes
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
/// <summary>
|
||||
/// Switches this PuppetMaster to PuppetMaster.Mode.Active.
|
||||
/// </summary>
|
||||
public void SwitchToActiveMode()
|
||||
{
|
||||
mode = Mode.Active;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches this PuppetMaster to PuppetMaster.Mode.Kinematic.
|
||||
/// </summary>
|
||||
public void SwitchToKinematicMode()
|
||||
{
|
||||
mode = Mode.Kinematic;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Switches this PuppetMaster to PuppetMaster.Mode.Disabled.
|
||||
/// </summary>
|
||||
public void SwitchToDisabledMode()
|
||||
{
|
||||
mode = Mode.Disabled;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the PuppetMaster is in the middle of blending from a mode to mode.
|
||||
/// </summary>
|
||||
public bool isSwitchingMode { get; private set; }
|
||||
|
||||
private Mode activeMode;
|
||||
private Mode lastMode;
|
||||
private float mappingBlend = 1f;
|
||||
|
||||
/// <summary>
|
||||
/// Disables the Puppet immediately without waiting for normal mode switching procedures.
|
||||
/// </summary>
|
||||
public void DisableImmediately() {
|
||||
mappingBlend = 0f;
|
||||
isSwitchingMode = false;
|
||||
mode = Mode.Disabled;
|
||||
activeMode = mode;
|
||||
lastMode = mode;
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
m.rigidbody.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Master controller for switching modes. Mode switching is done by simply changing PuppetMaster.mode and can not be interrupted.
|
||||
protected virtual void SwitchModes() {
|
||||
if (!initiated) return;
|
||||
if (isKilling) mode = Mode.Active;
|
||||
if (!isAlive) mode = Mode.Active;
|
||||
|
||||
foreach (BehaviourBase behaviour in behaviours) {
|
||||
if (behaviour.forceActive) {
|
||||
mode = Mode.Active;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (mode == lastMode) return;
|
||||
if (isSwitchingMode) return;
|
||||
if (isKilling && mode != Mode.Active) return;
|
||||
if (state != State.Alive && mode != Mode.Active) return;
|
||||
|
||||
// Enable state switching here or else mapping won't be blended correctly
|
||||
|
||||
isSwitchingMode = true;
|
||||
|
||||
if (lastMode == Mode.Disabled) {
|
||||
if (mode == Mode.Kinematic) DisabledToKinematic();
|
||||
else if (mode == Mode.Active) StartCoroutine(DisabledToActive());
|
||||
}
|
||||
|
||||
else if (lastMode == Mode.Kinematic) {
|
||||
if (mode == Mode.Disabled) KinematicToDisabled();
|
||||
else if (mode == Mode.Active) StartCoroutine(KinematicToActive());
|
||||
}
|
||||
|
||||
else if (lastMode == Mode.Active) {
|
||||
if (mode == Mode.Disabled) StartCoroutine(ActiveToDisabled());
|
||||
else if (mode == Mode.Kinematic) StartCoroutine(ActiveToKinematic());
|
||||
}
|
||||
|
||||
lastMode = mode;
|
||||
}
|
||||
|
||||
// Switch from Disabled to Kinematic mode
|
||||
private void DisabledToKinematic() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.Reset();
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.rigidbody.gameObject.SetActive(true);
|
||||
m.SetKinematic(true);
|
||||
}
|
||||
}
|
||||
|
||||
FlagInternalCollisionsForUpdate();
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.MoveToTarget();
|
||||
}
|
||||
|
||||
activeMode = Mode.Kinematic;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
|
||||
// Blend from Disabled to Active mode
|
||||
private IEnumerator DisabledToActive() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.Reset();
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.rigidbody.gameObject.SetActive(true);
|
||||
m.SetKinematic(false);
|
||||
m.rigidbody.WakeUp();
|
||||
m.rigidbody.velocity = m.mappedVelocity;
|
||||
m.rigidbody.angularVelocity = m.mappedAngularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
FlagInternalCollisionsForUpdate();
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.MoveToTarget();
|
||||
}
|
||||
|
||||
Read();
|
||||
|
||||
if (blendTime > 0f)
|
||||
{
|
||||
while (mappingBlend < 1f)
|
||||
{
|
||||
mappingBlend = Mathf.Clamp(mappingBlend + Time.deltaTime / blendTime, 0f, 1f);
|
||||
yield return null;
|
||||
}
|
||||
} else
|
||||
{
|
||||
mappingBlend = 1f;
|
||||
}
|
||||
|
||||
activeMode = Mode.Active;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
|
||||
// Switch from Kinematic to Disabled
|
||||
private void KinematicToDisabled() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.rigidbody.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
activeMode = Mode.Disabled;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
|
||||
// Blend from Kinematic to Active mode
|
||||
private IEnumerator KinematicToActive() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.SetKinematic(false);
|
||||
m.rigidbody.WakeUp();
|
||||
m.rigidbody.velocity = m.mappedVelocity;
|
||||
m.rigidbody.angularVelocity = m.mappedAngularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.MoveToTarget();
|
||||
}
|
||||
|
||||
Read();
|
||||
|
||||
if (blendTime > 0f)
|
||||
{
|
||||
while (mappingBlend < 1f)
|
||||
{
|
||||
mappingBlend = Mathf.Clamp(mappingBlend + Time.deltaTime / blendTime, 0f, 1f);
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
mappingBlend = 1f;
|
||||
}
|
||||
|
||||
activeMode = Mode.Active;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
|
||||
// Blend from Active to Disabled mode
|
||||
private IEnumerator ActiveToDisabled() {
|
||||
if (blendTime > 0f)
|
||||
{
|
||||
while (mappingBlend > 0f)
|
||||
{
|
||||
mappingBlend = Mathf.Max(mappingBlend - Time.deltaTime / blendTime, 0f);
|
||||
yield return null;
|
||||
}
|
||||
} else
|
||||
{
|
||||
mappingBlend = 0f;
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.rigidbody.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
activeMode = Mode.Disabled;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
|
||||
// Blend from Active to Kinematic mode
|
||||
private IEnumerator ActiveToKinematic() {
|
||||
if (blendTime > 0f)
|
||||
{
|
||||
while (mappingBlend > 0f)
|
||||
{
|
||||
mappingBlend = Mathf.Max(mappingBlend - Time.deltaTime / blendTime, 0f);
|
||||
yield return null;
|
||||
}
|
||||
} else
|
||||
{
|
||||
mappingBlend = 0f;
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.SetKinematic(true);
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected) m.MoveToTarget();
|
||||
}
|
||||
|
||||
activeMode = Mode.Kinematic;
|
||||
isSwitchingMode = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 77cc7f3b80a324aa3b61c57f1d536f34
|
||||
timeCreated: 1436431410
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,223 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Contains high level API calls for the PuppetMaster.
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for all muscles in the specified group.
|
||||
/// </summary>
|
||||
public void SetMuscleWeights(Muscle.Group group, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.props.group == group) {
|
||||
m.props.muscleWeight = muscleWeight;
|
||||
m.props.pinWeight = pinWeight;
|
||||
m.props.mappingWeight = mappingWeight;
|
||||
m.props.muscleDamper = muscleDamper;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle that has the humanBodyBone target (works only with a Humanoid avatar).
|
||||
/// </summary>
|
||||
public void SetMuscleWeights(Transform target, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
int index = GetMuscleIndex(target);
|
||||
if (index == -1) return;
|
||||
SetMuscleWeights(index, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle that has the humanBodyBone target (works only with a Humanoid avatar).
|
||||
/// </summary>
|
||||
public void SetMuscleWeights(HumanBodyBones humanBodyBone, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
int index = GetMuscleIndex(humanBodyBone);
|
||||
if (index == -1) return;
|
||||
SetMuscleWeights(index, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle with the specified target and all it's child muscles (when called on the upper arm, will set weights for the upper arm, forearm and hand of the same limb).
|
||||
/// </summary>
|
||||
public void SetMuscleWeightsRecursive(Transform target, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].target == target) {
|
||||
SetMuscleWeightsRecursive(i, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle of the specified muscle index and all it's child muscles (when called on the upper arm, will set weights for the upper arm, forearm and hand of the same limb).
|
||||
/// </summary>
|
||||
public void SetMuscleWeightsRecursive(int muscleIndex, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
SetMuscleWeights(muscleIndex, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
|
||||
for (int i = 0; i < muscles[muscleIndex].childIndexes.Length; i++) {
|
||||
int childIndex = muscles[muscleIndex].childIndexes[i];
|
||||
SetMuscleWeights(childIndex, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle that has the humanBodyBone target (works only with a Humanoid avatar) and all it's child muscles (when called on the upper arm, will set weights for the upper arm, forearm and hand of the same limb).
|
||||
/// </summary>
|
||||
public void SetMuscleWeightsRecursive(HumanBodyBones humanBodyBone, float muscleWeight, float pinWeight = 1f, float mappingWeight = 1f, float muscleDamper = 1f) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
int index = GetMuscleIndex(humanBodyBone);
|
||||
if (index == -1) return;
|
||||
SetMuscleWeightsRecursive(index, muscleWeight, pinWeight, mappingWeight, muscleDamper);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the muscle weights for the muscle with the specified index.
|
||||
/// </summary>
|
||||
public void SetMuscleWeights(int muscleIndex, float muscleWeight, float pinWeight, float mappingWeight, float muscleDamper) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
if (muscleIndex < 0f || muscleIndex >= muscles.Length) {
|
||||
Debug.LogWarning("Muscle index out of range (" + muscleIndex + ").", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
muscles[muscleIndex].props.muscleWeight = muscleWeight;
|
||||
muscles[muscleIndex].props.pinWeight = pinWeight;
|
||||
muscles[muscleIndex].props.mappingWeight = mappingWeight;
|
||||
muscles[muscleIndex].props.muscleDamper = muscleDamper;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the muscle that has the specified target.
|
||||
/// </summary>
|
||||
public Muscle GetMuscle(Transform target) {
|
||||
int index = GetMuscleIndex(target);
|
||||
if (index == -1) return null;
|
||||
return muscles[index];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the muscle of the specified Rigidbody.
|
||||
/// </summary>
|
||||
public Muscle GetMuscle(Rigidbody rigidbody) {
|
||||
int index = GetMuscleIndex(rigidbody);
|
||||
if (index == -1) return null;
|
||||
return muscles[index];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the muscle of the specified Joint.
|
||||
/// </summary>
|
||||
public Muscle GetMuscle(ConfigurableJoint joint) {
|
||||
int index = GetMuscleIndex(joint);
|
||||
if (index == -1) return null;
|
||||
return muscles[index];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Does the PuppetMaster have a muscle for the specified joint.
|
||||
/// </summary>
|
||||
public bool ContainsJoint(ConfigurableJoint joint) {
|
||||
if (!CheckIfInitiated()) return false;
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.joint == joint) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the muscle that has the humanBodyBone target (works only with a Humanoid avatar).
|
||||
/// </summary>
|
||||
public int GetMuscleIndex(HumanBodyBones humanBodyBone) {
|
||||
if (!CheckIfInitiated()) return -1;
|
||||
|
||||
if (targetAnimator == null) {
|
||||
Debug.LogWarning("PuppetMaster 'Target Root' has no Animator component on it nor on it's children.", transform);
|
||||
return -1;
|
||||
}
|
||||
if (!targetAnimator.isHuman) {
|
||||
Debug.LogWarning("PuppetMaster target's Animator does not belong to a Humanoid, can hot get human muscle index.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
var bone = targetAnimator.GetBoneTransform(humanBodyBone);
|
||||
if (bone == null) {
|
||||
Debug.LogWarning("PuppetMaster target's Avatar does not contain a bone Transform for " + humanBodyBone, transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
return GetMuscleIndex(bone);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the muscle that has the specified target. Returns -1 if not found.
|
||||
/// </summary>
|
||||
public int GetMuscleIndex(Transform target) {
|
||||
if (!CheckIfInitiated()) return -1;
|
||||
|
||||
if (target == null) {
|
||||
Debug.LogWarning("Target is null, can not get muscle index.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].target == target) return i;
|
||||
}
|
||||
|
||||
Debug.LogWarning("No muscle with target " + target.name + "found on the PuppetMaster.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the muscle that has the specified Rigidbody. Returns -1 if not found.
|
||||
/// </summary>
|
||||
public int GetMuscleIndex(Rigidbody rigidbody) {
|
||||
if (!CheckIfInitiated()) return -1;
|
||||
|
||||
if (rigidbody == null) {
|
||||
Debug.LogWarning("Rigidbody is null, can not get muscle index.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].rigidbody == rigidbody) return i;
|
||||
}
|
||||
|
||||
Debug.LogWarning("No muscle with Rigidbody " + rigidbody.name + "found on the PuppetMaster.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the index of the muscle that has the specified Joint. Returns -1 if not found.
|
||||
/// </summary>
|
||||
public int GetMuscleIndex(ConfigurableJoint joint) {
|
||||
if (joint == null) {
|
||||
Debug.LogWarning("Joint is null, can not get muscle index.", transform);
|
||||
return -1;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].joint == joint) return i;
|
||||
}
|
||||
|
||||
Debug.LogWarning("No muscle with Joint " + joint.name + "found on the PuppetMaster.", transform);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2037f2ed88fa7494186b86b64a821ab6
|
||||
timeCreated: 1436428162
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,289 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using RootMotion.Dynamics;
|
||||
using RootMotion;
|
||||
|
||||
namespace RootMotion.Dynamics
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// PuppetMaster prop designed to work with Prop Muscles.
|
||||
/// </summary>
|
||||
public class PuppetMasterProp : MonoBehaviour
|
||||
{
|
||||
[Tooltip("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.")]
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public Transform meshRoot;
|
||||
|
||||
[Tooltip("The muscle properties that will be applied to the Prop Muscle when this prop is picked up.")]
|
||||
/// <summary>
|
||||
/// The muscle properties that will be applied to the Prop Muscle when this prop is picked up.
|
||||
/// </summary>
|
||||
public Muscle.Props muscleProps;
|
||||
|
||||
[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;
|
||||
|
||||
[Tooltip("Mass of the prop while picked up. When dropped, mass of the original Rigidbody will be used.")]
|
||||
/// <summary>
|
||||
/// Mass of the prop while picked up. When dropped, mass of the original Rigidbody will be used.
|
||||
/// </summary>
|
||||
public float mass = 1f;
|
||||
|
||||
[Tooltip("This has no other purpose but helping you distinguish props by PropMuscle.currentProp.propType.")]
|
||||
/// <summary>
|
||||
/// This has no other purpose but helping you distinguish PropMuscle.currentProp by type.
|
||||
/// </summary>
|
||||
public int propType;
|
||||
|
||||
[LargeHeader("Materials")]
|
||||
|
||||
[Tooltip("If assigned, sets prop colliders to this PhysicMaterial when picked up. If no material assigned, will maintain the original PhysicMaterial (unless otherwise controlled by BehaviourPuppet's Group Overrides).")]
|
||||
/// <summary>
|
||||
/// If assigned, sets prop colliders to this PhysicMaterial when picked up. If no materials assigned here, will maintain the original PhysicMaterial.
|
||||
/// </summary>
|
||||
public PhysicMaterial pickedUpMaterial;
|
||||
|
||||
[LargeHeader("Additional Pin")]
|
||||
|
||||
[Tooltip("Adds this to Prop Muscle's 'Additional Pin Offset' when this prop is picked up.")]
|
||||
/// <summary>
|
||||
/// Adds this to Prop Muscle's 'Additional Pin Offset' when this prop is picked up.
|
||||
/// </summary>
|
||||
public Vector3 additionalPinOffsetAdd;
|
||||
|
||||
[Tooltip("The pin weight multiplier 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;
|
||||
|
||||
[Tooltip("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.")]
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public float additionalPinMass = 1f;
|
||||
|
||||
/// <summary>
|
||||
/// Is the prop currently picked up?
|
||||
/// </summary>
|
||||
public bool isPickedUp { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns either the Rigidbody of the prop when it is dropped or the Rigidbody of the prop muscle when it is picked up.
|
||||
/// </summary>
|
||||
public Rigidbody GetRigidbody()
|
||||
{
|
||||
if (r != null) return r;
|
||||
if (isPickedUp) return propMuscle.rigidbody;
|
||||
return null;
|
||||
}
|
||||
|
||||
protected virtual void OnPickUp(PuppetMaster puppetMaster, int propMuscleIndex) { }
|
||||
protected virtual void OnDrop(PuppetMaster puppetMaster, int propMuscleIndex) { }
|
||||
protected Muscle propMuscle { get; private set; }
|
||||
|
||||
private int defaultLayer;
|
||||
private Transform defaultParent;
|
||||
private Collider[] colliders = new Collider[0];
|
||||
private PhysicMaterial[] droppedMaterials = new PhysicMaterial[0];
|
||||
|
||||
private Rigidbody r;
|
||||
private float _mass;
|
||||
private float _drag;
|
||||
private float _angularDrag;
|
||||
private bool _useGravity;
|
||||
private bool _isKinematic;
|
||||
private RigidbodyInterpolation _interpolation;
|
||||
private CollisionDetectionMode _collisionDetectionMode;
|
||||
private RigidbodyConstraints _constraints;
|
||||
private Collider[] emptyColliders = new Collider[0];
|
||||
|
||||
// Called by PropMuscle when this prop is picked up
|
||||
public void PickUp(PuppetMaster puppetMaster, int propMuscleIndex)
|
||||
{
|
||||
RemoveRigidbody();
|
||||
|
||||
transform.parent = puppetMaster.muscles[propMuscleIndex].transform;
|
||||
transform.position = puppetMaster.muscles[propMuscleIndex].transform.position;
|
||||
transform.rotation = puppetMaster.muscles[propMuscleIndex].transform.rotation;
|
||||
|
||||
meshRoot.parent = puppetMaster.muscles[propMuscleIndex].target;
|
||||
meshRoot.localPosition = Vector3.zero;
|
||||
meshRoot.localRotation = Quaternion.identity;
|
||||
|
||||
puppetMaster.muscles[propMuscleIndex].props = muscleProps;
|
||||
|
||||
if (pickedUpMaterial != null)
|
||||
{
|
||||
foreach (Collider c in colliders)
|
||||
{
|
||||
c.sharedMaterial = pickedUpMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
if (forceLayers)
|
||||
{
|
||||
foreach (Collider c in colliders)
|
||||
{
|
||||
if (!c.isTrigger) c.gameObject.layer = puppetMaster.muscles[propMuscleIndex].joint.gameObject.layer;
|
||||
}
|
||||
}
|
||||
|
||||
puppetMaster.muscles[propMuscleIndex].colliders = colliders;
|
||||
puppetMaster.UpdateInternalCollisions(puppetMaster.muscles[propMuscleIndex]);
|
||||
|
||||
isPickedUp = true;
|
||||
propMuscle = puppetMaster.muscles[propMuscleIndex];
|
||||
|
||||
OnPickUp(puppetMaster, propMuscleIndex);
|
||||
}
|
||||
|
||||
// Called by PropMuscle when this prop is dropped
|
||||
public void Drop(PuppetMaster puppetMaster, int propMuscleIndex)
|
||||
{
|
||||
if (!puppetMaster.muscles[propMuscleIndex].joint.gameObject.activeInHierarchy)
|
||||
{
|
||||
transform.position = puppetMaster.muscles[propMuscleIndex].target.position;
|
||||
transform.rotation = puppetMaster.muscles[propMuscleIndex].target.rotation;
|
||||
}
|
||||
|
||||
ReattachRigidbody();
|
||||
|
||||
if (!puppetMaster.muscles[propMuscleIndex].joint.gameObject.activeInHierarchy || puppetMaster.muscles[propMuscleIndex].rigidbody.isKinematic)
|
||||
{
|
||||
r.velocity = puppetMaster.muscles[propMuscleIndex].mappedVelocity;
|
||||
r.angularVelocity = puppetMaster.muscles[propMuscleIndex].mappedAngularVelocity;
|
||||
}
|
||||
|
||||
transform.parent = defaultParent;
|
||||
|
||||
meshRoot.parent = transform;
|
||||
meshRoot.localPosition = Vector3.zero;
|
||||
meshRoot.localRotation = Quaternion.identity;
|
||||
|
||||
for (int i = 0; i < colliders.Length; i++)
|
||||
{
|
||||
colliders[i].sharedMaterial = droppedMaterials[i];
|
||||
}
|
||||
|
||||
puppetMaster.ResetInternalCollisions(puppetMaster.muscles[propMuscleIndex], false);
|
||||
puppetMaster.muscles[propMuscleIndex].colliders = emptyColliders;
|
||||
|
||||
if (forceLayers)
|
||||
{
|
||||
foreach (Collider c in colliders)
|
||||
{
|
||||
if (!c.isTrigger) c.gameObject.layer = defaultLayer;
|
||||
}
|
||||
}
|
||||
|
||||
isPickedUp = false;
|
||||
propMuscle = null;
|
||||
|
||||
OnDrop(puppetMaster, propMuscleIndex);
|
||||
}
|
||||
|
||||
protected virtual void Awake()
|
||||
{
|
||||
r = GetComponent<Rigidbody>();
|
||||
defaultParent = transform.parent;
|
||||
|
||||
colliders = GetComponentsInChildren<Collider>();
|
||||
|
||||
droppedMaterials = new PhysicMaterial[colliders.Length];
|
||||
for (int i = 0; i < colliders.Length; i++)
|
||||
{
|
||||
droppedMaterials[i] = colliders[i].sharedMaterial;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void Start()
|
||||
{
|
||||
muscleProps.group = Muscle.Group.Prop;
|
||||
|
||||
if (meshRoot == null)
|
||||
{
|
||||
Debug.LogError("PuppetMasterProp does not have a 'Mesh Root' Transform assigned.", transform);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
if (meshRoot == transform)
|
||||
{
|
||||
Debug.LogError("PuppetMasterProp's 'Mesh Root' can not be the PuppetMasterProp's own Transform.", transform);
|
||||
enabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
defaultLayer = gameObject.layer;
|
||||
foreach (Collider c in colliders)
|
||||
{
|
||||
if (!c.isTrigger)
|
||||
{
|
||||
defaultLayer = c.gameObject.layer;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual void Update()
|
||||
{
|
||||
if (isPickedUp)
|
||||
{
|
||||
transform.localPosition = Vector3.zero;
|
||||
transform.localRotation = Quaternion.identity;
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoveRigidbody()
|
||||
{
|
||||
if (r == null) return;
|
||||
|
||||
_mass = r.mass;
|
||||
_drag = r.drag;
|
||||
_angularDrag = r.angularDrag;
|
||||
_useGravity = r.useGravity;
|
||||
_isKinematic = r.isKinematic;
|
||||
_interpolation = r.interpolation;
|
||||
_collisionDetectionMode = r.collisionDetectionMode;
|
||||
_constraints = r.constraints;
|
||||
|
||||
Destroy(r);
|
||||
}
|
||||
|
||||
private void ReattachRigidbody()
|
||||
{
|
||||
if (r != null) return;
|
||||
|
||||
r = gameObject.AddComponent<Rigidbody>();
|
||||
r.mass = _mass;
|
||||
r.drag = _drag;
|
||||
r.angularDrag = _angularDrag;
|
||||
r.useGravity = _useGravity;
|
||||
r.isKinematic = _isKinematic;
|
||||
r.interpolation = _interpolation;
|
||||
r.collisionDetectionMode = _collisionDetectionMode;
|
||||
r.constraints = _constraints;
|
||||
}
|
||||
|
||||
void OnDrawGizmosSelected()
|
||||
{
|
||||
if (Application.isPlaying) return;
|
||||
|
||||
if (muscleProps != null) muscleProps.group = Muscle.Group.Prop;
|
||||
|
||||
if (meshRoot != null && meshRoot != transform)
|
||||
{
|
||||
meshRoot.parent = transform;
|
||||
|
||||
meshRoot.position = transform.position;
|
||||
meshRoot.rotation = transform.rotation;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 437d6ec63157d574988cc83cdc7c2dac
|
||||
timeCreated: 1550491014
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,124 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
/// <summary>
|
||||
/// The global master settings and optimizations for all PuppetMasters in the scene. Will only work if an instance of this singleton is added to the scene. If not, the PuppetMasters will use default values.
|
||||
/// </summary>
|
||||
[AddComponentMenu("Scripts/RootMotion.Dynamics/PuppetMaster/PuppetMaster Settings")]
|
||||
public class PuppetMasterSettings : Singleton <PuppetMasterSettings> {
|
||||
|
||||
[System.Serializable]
|
||||
public class PuppetUpdateLimit {
|
||||
[Range(1, 100)] public int puppetsPerFrame;
|
||||
|
||||
private int index;
|
||||
|
||||
public PuppetUpdateLimit() {
|
||||
this.puppetsPerFrame = 100;
|
||||
}
|
||||
|
||||
public void Step(int puppetCount) {
|
||||
index += puppetsPerFrame;
|
||||
if (index >= puppetCount) index -= puppetCount;
|
||||
}
|
||||
|
||||
public bool Update(List<PuppetMaster> puppets, PuppetMaster puppetMaster) {
|
||||
if (puppetsPerFrame >= puppets.Count) return true;
|
||||
|
||||
if (index >= puppets.Count) return false;
|
||||
|
||||
for (int i = 0; i < puppetsPerFrame; i++) {
|
||||
int o = index + i;
|
||||
if (o >= puppets.Count) o -= puppets.Count;
|
||||
|
||||
if (puppets[o] == puppetMaster) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Header("Optimizations")]
|
||||
|
||||
public PuppetUpdateLimit kinematicCollidersUpdateLimit = new PuppetUpdateLimit();
|
||||
public PuppetUpdateLimit freeUpdateLimit = new PuppetUpdateLimit();
|
||||
public PuppetUpdateLimit fixedUpdateLimit = new PuppetUpdateLimit();
|
||||
public bool collisionStayMessages = true;
|
||||
public bool collisionExitMessages = true;
|
||||
public float activePuppetCollisionThresholdMlp = 0f;
|
||||
|
||||
public int currentlyActivePuppets { get; private set; }
|
||||
public int currentlyKinematicPuppets { get; private set; }
|
||||
public int currentlyDisabledPuppets { get; private set; }
|
||||
|
||||
public List<PuppetMaster> puppets {
|
||||
get {
|
||||
return _puppets;
|
||||
}
|
||||
}
|
||||
|
||||
public void Register(PuppetMaster puppetMaster) {
|
||||
if (_puppets.Contains(puppetMaster)) return;
|
||||
_puppets.Add(puppetMaster);
|
||||
}
|
||||
|
||||
public void Unregister(PuppetMaster puppetMaster) {
|
||||
_puppets.Remove(puppetMaster);
|
||||
}
|
||||
|
||||
public bool UpdateMoveToTarget(PuppetMaster puppetMaster) {
|
||||
return kinematicCollidersUpdateLimit.Update(_puppets, puppetMaster);
|
||||
}
|
||||
|
||||
public bool UpdateFree(PuppetMaster puppetMaster) {
|
||||
return freeUpdateLimit.Update(_puppets, puppetMaster);
|
||||
}
|
||||
|
||||
public bool UpdateFixed(PuppetMaster puppetMaster) {
|
||||
return fixedUpdateLimit.Update(_puppets, puppetMaster);
|
||||
}
|
||||
|
||||
private List<PuppetMaster> _puppets = new List<PuppetMaster>();
|
||||
//private int optIndexMoveToTarget;
|
||||
//private int optIndexFixed;
|
||||
|
||||
void Update() {
|
||||
currentlyActivePuppets = 0;
|
||||
currentlyKinematicPuppets = 0;
|
||||
currentlyDisabledPuppets = 0;
|
||||
|
||||
foreach (PuppetMaster puppet in _puppets) {
|
||||
if (puppet.isActive && puppet.isActiveAndEnabled) currentlyActivePuppets ++;
|
||||
if (puppet.mode == PuppetMaster.Mode.Kinematic) currentlyKinematicPuppets ++;
|
||||
if ((puppet.mode == PuppetMaster.Mode.Disabled && !puppet.isActive) || !puppet.isActiveAndEnabled) currentlyDisabledPuppets ++;
|
||||
}
|
||||
|
||||
freeUpdateLimit.Step(_puppets.Count);
|
||||
kinematicCollidersUpdateLimit.Step(_puppets.Count);
|
||||
}
|
||||
|
||||
void FixedUpdate() {
|
||||
fixedUpdateLimit.Step(_puppets.Count);
|
||||
|
||||
/*
|
||||
optIndexMoveToTarget += updateKinematicCollidersLimit;
|
||||
if (optIndexMoveToTarget >= puppets.Count) optIndexMoveToTarget -= _puppets.Count;
|
||||
|
||||
optIndexFixed += updatePuppetsFixedFrameLimit;
|
||||
if (optIndexFixed >= puppets.Count) optIndexFixed -= _puppets.Count;
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
void OnGUI() {
|
||||
GUILayout.Label("Active puppets: " + currentlyActivePuppets.ToString());
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: dc1cfd8a0119540e8970180fc708afbd
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,308 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Code for setting up Puppets.
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
/// <summary>
|
||||
/// Sets up a Puppet from the specified ragdoll and target characters.
|
||||
/// </summary>
|
||||
public static PuppetMaster SetUp(Transform target, Transform ragdoll, int characterControllerLayer, int ragdollLayer) {
|
||||
if (ragdoll != target) {
|
||||
PuppetMaster puppetMaster = ragdoll.gameObject.AddComponent<PuppetMaster>();
|
||||
puppetMaster.SetUpTo(target, characterControllerLayer, ragdollLayer);
|
||||
return puppetMaster;
|
||||
} else {
|
||||
return SetUp(ragdoll, characterControllerLayer, ragdollLayer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets up a Puppet using a single ragdoll character. This will duplicate the ragdoll character, remove the ragdoll components from the original and use it as the animated target.
|
||||
/// </summary>
|
||||
public static PuppetMaster SetUp(Transform target, int characterControllerLayer, int ragdollLayer) {
|
||||
Transform ragdoll = ((GameObject)GameObject.Instantiate(target.gameObject, target.position, target.rotation)).transform;
|
||||
|
||||
PuppetMaster puppetMaster = ragdoll.gameObject.AddComponent<PuppetMaster>();
|
||||
puppetMaster.SetUpTo(target, characterControllerLayer, ragdollLayer);
|
||||
|
||||
// Clean up the target from all the ragdoll components
|
||||
RemoveRagdollComponents(target, characterControllerLayer);
|
||||
|
||||
return puppetMaster;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the ragdoll up as a Puppet. Assigns the specified layers to the animated target and the ragdoll. If setUpTo is the same Transform as the PuppetMaster's, the character will be duplicated and the duplicate will be used as the animated target.
|
||||
/// </summary>
|
||||
public void SetUpTo(Transform setUpTo, int characterControllerLayer, int ragdollLayer) {
|
||||
if (setUpTo == null) {
|
||||
Debug.LogWarning("SetUpTo is null. Can not set the PuppetMaster up to a null Transform.",transform);
|
||||
return;
|
||||
}
|
||||
|
||||
// Setting up the ragdoll to itself
|
||||
if (setUpTo == transform) {
|
||||
setUpTo = ((GameObject)GameObject.Instantiate(setUpTo.gameObject, setUpTo.position, setUpTo.rotation)).transform;
|
||||
setUpTo.name = name;
|
||||
|
||||
// Clean up the target from all the ragdoll components
|
||||
RemoveRagdollComponents(setUpTo, characterControllerLayer);
|
||||
}
|
||||
|
||||
RemoveUnnecessaryBones();
|
||||
|
||||
/*
|
||||
Animator[] animators = GetComponentsInChildren<Animator>();
|
||||
for (int i = 0; i < animators.Length; i++) {
|
||||
DestroyImmediate(animators[i]);
|
||||
}
|
||||
|
||||
Animation[] animations = GetComponentsInChildren<Animation>();
|
||||
for (int i = 0; i < animations.Length; i++) {
|
||||
DestroyImmediate(animations[i]);
|
||||
}
|
||||
*/
|
||||
|
||||
Component[] components = GetComponentsInChildren<Component>();
|
||||
for (int i = 0; i < components.Length; i++) {
|
||||
if (components[i] is PuppetMaster
|
||||
|| components[i] is Transform
|
||||
|| components[i] is Rigidbody
|
||||
|| components[i] is BoxCollider
|
||||
|| components[i] is CapsuleCollider
|
||||
|| components[i] is SphereCollider
|
||||
|| components[i] is MeshCollider
|
||||
|| components[i] is Joint
|
||||
|| components[i] is Animator) {
|
||||
} else DestroyImmediate(components[i]);
|
||||
}
|
||||
|
||||
// Destroy Animators last, in case some components require it (ThirdPersonCharacter)
|
||||
Animator[] animators = GetComponentsInChildren<Animator>();
|
||||
for (int i = 0; i < animators.Length; i++) {
|
||||
DestroyImmediate(animators[i]);
|
||||
}
|
||||
|
||||
// Remove everything except PuppetMaster and Transform from this component
|
||||
components = transform.GetComponents<Component>();
|
||||
for (int i = 0; i < components.Length; i++) {
|
||||
if (components[i] is PuppetMaster || components[i] is Transform) {
|
||||
} else DestroyImmediate(components[i]);
|
||||
}
|
||||
|
||||
//JointConverter.ToConfigurable(gameObject);
|
||||
|
||||
// Add ConfigurableJoints to Rigidbodies that don't have a Joint (Pelvis and other free muscles)
|
||||
Rigidbody[] rigidbodies = transform.GetComponentsInChildren<Rigidbody>();
|
||||
foreach (Rigidbody r in rigidbodies) {
|
||||
if (r.transform != transform && r.GetComponent<ConfigurableJoint>() == null) {
|
||||
r.gameObject.AddComponent<ConfigurableJoint>();
|
||||
}
|
||||
}
|
||||
|
||||
targetRoot = setUpTo;
|
||||
|
||||
// Auto-detect targets
|
||||
SetUpMuscles(setUpTo);
|
||||
|
||||
name = "PuppetMaster";
|
||||
|
||||
bool newParent = setUpTo.parent == null || setUpTo.parent != transform.parent || setUpTo.parent.name != setUpTo.name + " Root";
|
||||
Transform root = newParent? new GameObject(setUpTo.name + " Root").transform: setUpTo.parent;
|
||||
root.parent = transform.parent;
|
||||
|
||||
Transform behaviourRoot = new GameObject("Behaviours").transform;
|
||||
Comments comments = behaviourRoot.gameObject.GetComponent<Comments>();
|
||||
if (comments == null) comments = behaviourRoot.gameObject.AddComponent<Comments>();
|
||||
comments.text = "All Puppet Behaviours should be parented to this GameObject, the PuppetMaster will automatically find them from here. All Puppet Behaviours have been designed so that they could be simply copied from one character to another without changing any references. It is important because they contain a lot of parameters and would be otherwise tedious to set up and tweak.";
|
||||
|
||||
root.position = setUpTo.position;
|
||||
root.rotation = setUpTo.rotation;
|
||||
behaviourRoot.position = setUpTo.position;
|
||||
behaviourRoot.rotation = setUpTo.rotation;
|
||||
transform.position = setUpTo.position;
|
||||
transform.rotation = setUpTo.rotation;
|
||||
|
||||
behaviourRoot.parent = root;
|
||||
transform.parent = root;
|
||||
setUpTo.parent = root;
|
||||
|
||||
// Layers
|
||||
targetRoot.gameObject.layer = characterControllerLayer;
|
||||
|
||||
gameObject.layer = ragdollLayer;
|
||||
foreach (Muscle m in muscles) m.joint.gameObject.layer = ragdollLayer;
|
||||
|
||||
Physics.IgnoreLayerCollision(characterControllerLayer, ragdollLayer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes all the ragdoll components (except Cloth colliders), including compound colliders that are not used by Cloth. Components on the 'target' GameObject will not be touched for they are probably not ragdoll components, but required by a character controller.
|
||||
/// </summary>
|
||||
/// <param name="target">Target.</param>
|
||||
public static void RemoveRagdollComponents(Transform target, int characterControllerLayer) {
|
||||
if (target == null) return;
|
||||
|
||||
// Get rid of all the ragdoll components on the target
|
||||
Rigidbody[] rigidbodies = target.GetComponentsInChildren<Rigidbody>();
|
||||
Cloth[] cloths = target.GetComponentsInChildren<Cloth>();
|
||||
|
||||
for (int i = 0; i < rigidbodies.Length; i++) {
|
||||
if (rigidbodies[i].gameObject != target.gameObject) {
|
||||
var joint = rigidbodies[i].GetComponent<Joint>();
|
||||
var collider = rigidbodies[i].GetComponent<Collider>();
|
||||
|
||||
if (joint != null) DestroyImmediate(joint);
|
||||
if (collider != null) {
|
||||
if (!IsClothCollider(collider, cloths)) DestroyImmediate(collider);
|
||||
else collider.gameObject.layer = characterControllerLayer;
|
||||
}
|
||||
DestroyImmediate(rigidbodies[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Get rid of (compound) colliders that are not used by Cloth
|
||||
Collider[] colliders = target.GetComponentsInChildren<Collider>();
|
||||
|
||||
for (int i = 0; i < colliders.Length; i++) {
|
||||
if (colliders[i].transform != target && !IsClothCollider(colliders[i], cloths)) {
|
||||
DestroyImmediate(colliders[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Get rid of the PuppetMaster
|
||||
var puppetMaster = target.GetComponent<PuppetMaster>();
|
||||
if (puppetMaster != null) DestroyImmediate(puppetMaster);
|
||||
}
|
||||
|
||||
// Builds muscles
|
||||
private void SetUpMuscles(Transform setUpTo) {
|
||||
// Auto-detect targets
|
||||
ConfigurableJoint[] joints = transform.GetComponentsInChildren<ConfigurableJoint>();
|
||||
|
||||
if (joints.Length == 0) {
|
||||
Debug.LogWarning("No ConfigurableJoints found, can not build PuppetMaster. Please create ConfigurableJoints to connect the ragdoll bones together.", transform);
|
||||
return;
|
||||
}
|
||||
|
||||
var animator = targetRoot.GetComponentInChildren<Animator>();
|
||||
Transform[] children = setUpTo.GetComponentsInChildren<Transform>();
|
||||
|
||||
muscles = new Muscle[joints.Length];
|
||||
int hipIndex = -1;
|
||||
|
||||
for (int i = 0; i < joints.Length; i++) {
|
||||
muscles[i] = new Muscle();
|
||||
muscles[i].joint = joints[i];
|
||||
muscles[i].name = joints[i].name;
|
||||
muscles[i].props = new Muscle.Props(1f, 1f, 1f, 1f, muscles[i].joint.connectedBody == null);
|
||||
if (muscles[i].joint.connectedBody == null && hipIndex == -1) hipIndex = i;
|
||||
|
||||
foreach (Transform c in children) {
|
||||
if (c.name == joints[i].name) {
|
||||
muscles[i].target = c;
|
||||
if (animator != null) {
|
||||
muscles[i].props.group = FindGroup(animator, muscles[i].target);
|
||||
|
||||
if (muscles[i].props.group == Muscle.Group.Hips || muscles[i].props.group == Muscle.Group.Leg || muscles[i].props.group == Muscle.Group.Foot) {
|
||||
muscles[i].props.mapPosition = true;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The hip muscle is not first in hierarchy
|
||||
if (hipIndex != 0) {
|
||||
var firstMuscle = muscles[0];
|
||||
var hipMuscle = muscles[hipIndex];
|
||||
muscles[hipIndex] = firstMuscle;
|
||||
muscles[0] = hipMuscle;
|
||||
}
|
||||
|
||||
bool allSameGroup = true;
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.target == null) {
|
||||
Debug.LogWarning("No target Transform found for PuppetMaster muscle " + m.joint.name + ". Please assign manually.", transform);
|
||||
}
|
||||
|
||||
if (m.props.group != muscles[0].props.group) allSameGroup = false;
|
||||
}
|
||||
|
||||
if (allSameGroup) {
|
||||
Debug.LogWarning("Muscle groups need to be assigned in the PuppetMaster!", transform);
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the Muscle.Group of the specified bone Transform (only if using the Humanoid rig)
|
||||
private static Muscle.Group FindGroup(Animator animator, Transform t) {
|
||||
if (!animator.isHuman) return Muscle.Group.Hips;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.Chest)) return Muscle.Group.Spine;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.Head)) return Muscle.Group.Head;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.Hips)) return Muscle.Group.Hips;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftFoot)) return Muscle.Group.Foot;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftHand)) return Muscle.Group.Hand;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftLowerArm)) return Muscle.Group.Arm;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftLowerLeg)) return Muscle.Group.Leg;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftUpperArm)) return Muscle.Group.Arm;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.LeftUpperLeg)) return Muscle.Group.Leg;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightFoot)) return Muscle.Group.Foot;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightHand)) return Muscle.Group.Hand;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightLowerArm)) return Muscle.Group.Arm;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightLowerLeg)) return Muscle.Group.Leg;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightUpperArm)) return Muscle.Group.Arm;
|
||||
if (t == animator.GetBoneTransform(HumanBodyBones.RightUpperLeg)) return Muscle.Group.Leg;
|
||||
return Muscle.Group.Spine;
|
||||
}
|
||||
|
||||
// Removes all bones that don't have a Rigidbody or a Collider attached because they are not part of the simulation
|
||||
private void RemoveUnnecessaryBones() {
|
||||
Transform[] children = GetComponentsInChildren<Transform>();
|
||||
for (int i = 1; i < children.Length; i++) {
|
||||
bool keep = false;
|
||||
|
||||
if (children[i].GetComponent<Rigidbody>() != null || children[i].GetComponent<ConfigurableJoint>() != null) keep = true; // Ragdoll bone
|
||||
if (children[i].GetComponent<Collider>() != null && children[i].GetComponent<Rigidbody>() == null) keep = true; // Compound collider
|
||||
if (children[i].GetComponent<CharacterController>() != null) keep = false; // Character controller
|
||||
|
||||
if (!keep) {
|
||||
Transform[] save = new Transform[children[i].childCount];
|
||||
for (int c = 0; c < save.Length; c++) {
|
||||
save[c] = children[i].GetChild(c);
|
||||
}
|
||||
|
||||
for (int c = 0; c < save.Length; c++) {
|
||||
save[c].parent = children[i].parent;
|
||||
}
|
||||
|
||||
DestroyImmediate(children[i].gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if the collider is used by the Cloth.
|
||||
private static bool IsClothCollider(Collider collider, Cloth[] cloths) {
|
||||
if (cloths == null) return false;
|
||||
|
||||
foreach (Cloth cloth in cloths) {
|
||||
if (cloth == null) return false;
|
||||
foreach (CapsuleCollider c in cloth.capsuleColliders) {
|
||||
if (c != null && c.gameObject == collider.gameObject) return true;
|
||||
}
|
||||
foreach (ClothSphereColliderPair s in cloth.sphereColliders) {
|
||||
if (s.first != null && s.first.gameObject == collider.gameObject) return true;
|
||||
if (s.second != null && s.second.gameObject == collider.gameObject) return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 73e3c624eebb841dda0e78f86c01c076
|
||||
timeCreated: 1436432142
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,388 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Switching and blending between Modes
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
[System.Serializable]
|
||||
public enum State {
|
||||
Alive,
|
||||
Dead,
|
||||
Frozen
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public struct StateSettings {
|
||||
|
||||
[TooltipAttribute("How much does it take to weigh out muscle weight to deadMuscleWeight?")]
|
||||
public float killDuration;
|
||||
|
||||
[TooltipAttribute("The muscle weight mlp while the puppet is Dead.")]
|
||||
public float deadMuscleWeight;
|
||||
|
||||
[TooltipAttribute("The muscle damper add while the puppet is Dead.")]
|
||||
public float deadMuscleDamper;
|
||||
|
||||
[TooltipAttribute("The max square velocity of the ragdoll bones for freezing the puppet.")]
|
||||
public float maxFreezeSqrVelocity;
|
||||
|
||||
[TooltipAttribute("If true, PuppetMaster, all it's behaviours and the ragdoll will be destroyed when the puppet is frozen.")]
|
||||
public bool freezePermanently;
|
||||
|
||||
[TooltipAttribute("If true, will enable angular limits when killing the puppet.")]
|
||||
public bool enableAngularLimitsOnKill;
|
||||
|
||||
[TooltipAttribute("If true, will enable internal collisions when killing the puppet.")]
|
||||
public bool enableInternalCollisionsOnKill;
|
||||
|
||||
public StateSettings(float killDuration, float deadMuscleWeight = 0.01f, float deadMuscleDamper = 2f, float maxFreezeSqrVelocity = 0.02f, bool freezePermanently = false, bool enableAngularLimitsOnKill = true, bool enableInternalCollisionsOnKill = true) {
|
||||
this.killDuration = killDuration;
|
||||
this.deadMuscleWeight = deadMuscleWeight;
|
||||
this.deadMuscleDamper = deadMuscleDamper;
|
||||
this.maxFreezeSqrVelocity = maxFreezeSqrVelocity;
|
||||
this.freezePermanently = freezePermanently;
|
||||
this.enableAngularLimitsOnKill = enableAngularLimitsOnKill;
|
||||
this.enableInternalCollisionsOnKill = enableInternalCollisionsOnKill;
|
||||
}
|
||||
|
||||
public static StateSettings Default {
|
||||
get {
|
||||
return new StateSettings(1f, 0.01f, 2f, 0.02f, false, true, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if PuppetMaster is in the middle of switching states. Don't deactivate the PuppetMaster nor any of it's behaviours while it returns true.
|
||||
/// </summary>
|
||||
public bool isSwitchingState {
|
||||
get {
|
||||
return activeState != state;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Is the puppet in the middle of a killing procedure (started by PuppetMaster.Kill())?
|
||||
/// </summary>
|
||||
public bool isKilling { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Is the puppet alive or still dying?
|
||||
/// </summary>
|
||||
public bool isAlive { get { return activeState == State.Alive; }}
|
||||
|
||||
/// <summary>
|
||||
/// Is the puppet frozen?
|
||||
/// </summary>
|
||||
public bool isFrozen { get { return activeState == State.Frozen; }}
|
||||
|
||||
/// <summary>
|
||||
/// Kill the puppet with the specified StateSettings
|
||||
/// </summary>
|
||||
public void Kill() {
|
||||
state = State.Dead;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kill the puppet with the specified StateSettings
|
||||
/// </summary>
|
||||
public void Kill(StateSettings stateSettings) {
|
||||
this.stateSettings = stateSettings;
|
||||
state = State.Dead;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unfreeze the puppet with the specified StateSettings.
|
||||
/// </summary>
|
||||
public void Freeze() {
|
||||
state = State.Frozen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unfreeze the puppet with the specified StateSettings.
|
||||
/// </summary>
|
||||
public void Freeze(StateSettings stateSettings) {
|
||||
this.stateSettings = stateSettings;
|
||||
state = State.Frozen;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resurrect this instance from the Dead or Frozen state (unless frozen permanently).
|
||||
/// </summary>
|
||||
public void Resurrect() {
|
||||
state = State.Alive;
|
||||
}
|
||||
|
||||
public UpdateDelegate OnFreeze;
|
||||
public UpdateDelegate OnUnfreeze;
|
||||
public UpdateDelegate OnDeath;
|
||||
public UpdateDelegate OnResurrection;
|
||||
|
||||
private State activeState;
|
||||
private State lastState;
|
||||
private bool angularLimitsEnabledOnKill;
|
||||
private bool internalCollisionsEnabledOnKill;
|
||||
private bool animationDisabledbyStates;
|
||||
|
||||
// Master controller for switching modes. Mode switching is done by simply changing PuppetMaster.mode and can not be interrupted.
|
||||
protected virtual void SwitchStates() {
|
||||
if (state == lastState) return;
|
||||
if (isKilling) return;
|
||||
|
||||
if (freezeFlag) {
|
||||
if (state == State.Alive) {
|
||||
activeState = State.Dead;
|
||||
lastState = State.Dead;
|
||||
freezeFlag = false;
|
||||
}
|
||||
else if (state == State.Dead) {
|
||||
lastState = State.Dead;
|
||||
freezeFlag = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (freezeFlag) return;
|
||||
}
|
||||
|
||||
if (lastState == State.Alive) {
|
||||
if (state == State.Dead) StartCoroutine(AliveToDead(false));
|
||||
else if (state == State.Frozen) StartCoroutine(AliveToDead(true));
|
||||
}
|
||||
else if (lastState == State.Dead) {
|
||||
if (state == State.Alive) DeadToAlive();
|
||||
else if (state == State.Frozen) DeadToFrozen();
|
||||
}
|
||||
else if (lastState == State.Frozen) {
|
||||
if (state == State.Alive) FrozenToAlive();
|
||||
else if (state == State.Dead) FrozenToDead();
|
||||
}
|
||||
|
||||
lastState = state;
|
||||
}
|
||||
|
||||
private IEnumerator AliveToDead(bool freeze) {
|
||||
isKilling = true;
|
||||
|
||||
mode = Mode.Active;
|
||||
|
||||
if (stateSettings.enableAngularLimitsOnKill) {
|
||||
if (!angularLimits) {
|
||||
angularLimits = true;
|
||||
angularLimitsEnabledOnKill = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (stateSettings.enableInternalCollisionsOnKill) {
|
||||
if (!internalCollisions) {
|
||||
internalCollisions = true;
|
||||
internalCollisionsEnabledOnKill = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Set pin weight to 0 to play with joint target rotations only
|
||||
foreach (Muscle m in muscles) {
|
||||
if (!m.state.isDisconnected)
|
||||
{
|
||||
m.state.pinWeightMlp = 0f;
|
||||
m.state.muscleDamperAdd = stateSettings.deadMuscleDamper;
|
||||
|
||||
m.rigidbody.velocity = m.mappedVelocity;
|
||||
m.rigidbody.angularVelocity = m.mappedAngularVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
float range = muscles[0].state.muscleWeightMlp - stateSettings.deadMuscleWeight;
|
||||
foreach (BehaviourBase behaviour in behaviours) behaviour.KillStart();
|
||||
|
||||
if (stateSettings.killDuration > 0f && range > 0f) {
|
||||
float mW = muscles[0].state.muscleWeightMlp;
|
||||
|
||||
while (mW > stateSettings.deadMuscleWeight) {
|
||||
mW = Mathf.Max(mW - Time.deltaTime * (range / stateSettings.killDuration), stateSettings.deadMuscleWeight);
|
||||
|
||||
foreach (Muscle m in muscles) m.state.muscleWeightMlp = mW;
|
||||
|
||||
yield return null;
|
||||
}
|
||||
}
|
||||
foreach (Muscle m in muscles) m.state.muscleWeightMlp = stateSettings.deadMuscleWeight;
|
||||
|
||||
// Disable the Animator
|
||||
SetAnimationEnabled(false);
|
||||
|
||||
isKilling = false;
|
||||
activeState = State.Dead;
|
||||
|
||||
if (freeze) freezeFlag = true;
|
||||
foreach (BehaviourBase behaviour in behaviours) behaviour.KillEnd();
|
||||
|
||||
if (OnDeath != null) OnDeath();
|
||||
}
|
||||
|
||||
private void OnFreezeFlag() {
|
||||
if (!CanFreeze()) return;
|
||||
|
||||
SetAnimationEnabled(false);
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
m.joint.gameObject.SetActive(false);
|
||||
}
|
||||
|
||||
foreach (BehaviourBase behaviour in behaviours) {
|
||||
behaviour.Freeze();
|
||||
|
||||
if (behaviour.gameObject.activeSelf) {
|
||||
behaviour.deactivated = true;
|
||||
behaviour.gameObject.SetActive(false);
|
||||
}
|
||||
}
|
||||
|
||||
freezeFlag = false;
|
||||
activeState = State.Frozen;
|
||||
|
||||
if (OnFreeze != null) OnFreeze();
|
||||
|
||||
if (stateSettings.freezePermanently) {
|
||||
if (behaviours.Length > 0 && behaviours[0] != null) {
|
||||
Destroy(behaviours[0].transform.parent.gameObject);
|
||||
}
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
|
||||
private void DeadToAlive() {
|
||||
foreach (Muscle m in muscles) {
|
||||
m.state.pinWeightMlp = 1f;
|
||||
m.state.muscleWeightMlp = 1f;
|
||||
m.state.muscleDamperAdd = 0f;
|
||||
}
|
||||
|
||||
if (angularLimitsEnabledOnKill) {
|
||||
angularLimits = false;
|
||||
angularLimitsEnabledOnKill = false;
|
||||
}
|
||||
if (internalCollisionsEnabledOnKill) {
|
||||
internalCollisions = false;
|
||||
internalCollisionsEnabledOnKill = false;
|
||||
}
|
||||
|
||||
// Reset all
|
||||
foreach (BehaviourBase b in behaviours) {
|
||||
b.Resurrect();
|
||||
}
|
||||
|
||||
SetAnimationEnabled(true);
|
||||
|
||||
activeState = State.Alive;
|
||||
if (OnResurrection != null) OnResurrection();
|
||||
}
|
||||
|
||||
private void SetAnimationEnabled(bool to) {
|
||||
// What if animator not disabled while still dying?
|
||||
//if (!to) animationDisabledbyStates = true;
|
||||
//else if (!animationDisabledbyStates) return;
|
||||
|
||||
animatorDisabled = false;
|
||||
|
||||
if (targetAnimator != null) {
|
||||
targetAnimator.enabled = to;
|
||||
//if (to) targetAnimator.Update(0.001f); // Don't do this when getting up, will flicker animated pose for a moment
|
||||
}
|
||||
|
||||
if (targetAnimation != null) targetAnimation.enabled = to;
|
||||
}
|
||||
|
||||
private void DeadToFrozen() {
|
||||
freezeFlag = true;
|
||||
}
|
||||
|
||||
private void FrozenToAlive() {
|
||||
freezeFlag = false;
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
m.state.pinWeightMlp = 1f;
|
||||
m.state.muscleWeightMlp = 1f;
|
||||
m.state.muscleDamperAdd = 0f;
|
||||
}
|
||||
|
||||
if (angularLimitsEnabledOnKill) {
|
||||
angularLimits = false;
|
||||
angularLimitsEnabledOnKill = false;
|
||||
}
|
||||
if (internalCollisionsEnabledOnKill) {
|
||||
internalCollisions = false;
|
||||
internalCollisionsEnabledOnKill = false;
|
||||
}
|
||||
|
||||
ActivateRagdoll();
|
||||
|
||||
foreach (BehaviourBase behaviour in behaviours) {
|
||||
behaviour.Unfreeze();
|
||||
behaviour.Resurrect();
|
||||
|
||||
if (behaviour.deactivated) behaviour.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
if (targetAnimator != null) targetAnimator.enabled = true;
|
||||
if (targetAnimation != null) targetAnimation.enabled = true;
|
||||
|
||||
activeState = State.Alive;
|
||||
|
||||
if (OnUnfreeze != null) OnUnfreeze();
|
||||
if (OnResurrection != null) OnResurrection();
|
||||
}
|
||||
|
||||
private void FrozenToDead() {
|
||||
freezeFlag = false;
|
||||
|
||||
ActivateRagdoll();
|
||||
|
||||
foreach (BehaviourBase behaviour in behaviours) {
|
||||
behaviour.Unfreeze();
|
||||
|
||||
if (behaviour.deactivated) behaviour.gameObject.SetActive(true);
|
||||
}
|
||||
|
||||
activeState = State.Dead;
|
||||
if (OnUnfreeze != null) OnUnfreeze();
|
||||
}
|
||||
|
||||
private void ActivateRagdoll(bool kinematic = false) {
|
||||
foreach (Muscle m in muscles) {
|
||||
m.Reset();
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
m.joint.gameObject.SetActive(true);
|
||||
if (kinematic) m.rigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;
|
||||
m.SetKinematic(kinematic);
|
||||
m.rigidbody.velocity = Vector3.zero;
|
||||
m.rigidbody.angularVelocity = Vector3.zero;
|
||||
}
|
||||
|
||||
FlagInternalCollisionsForUpdate();
|
||||
|
||||
// Fix target to whatever it was mapped to last frame
|
||||
//SampleTargetMappedState();
|
||||
//FixTargetToSampledState(1f);
|
||||
|
||||
|
||||
Read();
|
||||
|
||||
foreach (Muscle m in muscles) {
|
||||
m.MoveToTarget();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private bool CanFreeze() {
|
||||
foreach (Muscle m in muscles) {
|
||||
if (m.rigidbody.velocity.sqrMagnitude > stateSettings.maxFreezeSqrVelocity) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f4e273f7a112e4062a3d34c07bb21678
|
||||
timeCreated: 1452674686
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,236 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Code for storing and sampling mapped poses of the animated target and blending back to the last sampled mapped pose.
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
/// <summary>
|
||||
/// Store the mapped state of the target automatically?
|
||||
/// </summary>
|
||||
[HideInInspector] public bool storeTargetMappedState = true;
|
||||
|
||||
/// <summary>
|
||||
/// The pose that the target will be fixed to if calling FixTargetToSampledState(). This should normally be used only by the Puppet Behaviours.
|
||||
/// </summary>
|
||||
public void SampleTargetMappedState() {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
sampleTargetMappedState = true;
|
||||
|
||||
if (!targetMappedStateStored)
|
||||
{
|
||||
sampleTargetMappedState = true;
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++)
|
||||
{
|
||||
if (i == 0) muscles[i].targetSampledPosition = muscles[i].targetMappedPosition;
|
||||
muscles[i].targetSampledRotation = muscles[i].targetMappedRotation;
|
||||
}
|
||||
|
||||
targetMappedStateSampled = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blend the target to the pose that was sampled by the last SampleTargetMappedState call. This should normally be used only by the Puppet Behaviours.
|
||||
/// </summary>
|
||||
public void FixTargetToSampledState(float weight) {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
if (weight <= 0f) return;
|
||||
|
||||
if (!targetMappedStateSampled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++)
|
||||
{
|
||||
if (i == 0) muscles[i].target.position = Vector3.Lerp(muscles[i].target.position, muscles[i].targetSampledPosition, weight);
|
||||
muscles[i].target.rotation = Quaternion.Lerp(muscles[i].target.rotation, muscles[i].targetSampledRotation, weight);
|
||||
}
|
||||
|
||||
foreach (Muscle m in muscles) m.positionOffset = m.target.position - m.rigidbody.position;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the current pose of the target for sampling. This should normally be used only by the Puppet Behaviours.
|
||||
/// </summary>
|
||||
public void StoreTargetMappedState() {
|
||||
if (!CheckIfInitiated()) return;
|
||||
|
||||
if (!storeTargetMappedState) return;
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++)
|
||||
{
|
||||
if (i == 0) muscles[i].StoreTargetMappedPosition();
|
||||
muscles[i].StoreTargetMappedRotation();
|
||||
}
|
||||
|
||||
targetMappedStateStored = true;
|
||||
|
||||
if (sampleTargetMappedState) SampleTargetMappedState();
|
||||
sampleTargetMappedState = false;
|
||||
}
|
||||
|
||||
private bool targetMappedStateStored;
|
||||
private bool targetMappedStateSampled;
|
||||
private bool sampleTargetMappedState;
|
||||
private bool hasProp;
|
||||
|
||||
// Should be called each time the puppet structure is changed
|
||||
private void UpdateHierarchies() {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
muscles[i].index = i;
|
||||
if (muscles[i].broadcaster != null) muscles[i].broadcaster.muscleIndex = i;
|
||||
if (muscles[i].jointBreakBroadcaster != null) muscles[i].jointBreakBroadcaster.muscleIndex = i;
|
||||
}
|
||||
|
||||
targetMappedStateStored = false;
|
||||
targetMappedStateSampled = false;
|
||||
|
||||
AssignParentAndChildIndexes();
|
||||
AssignKinshipDegrees();
|
||||
UpdateBroadcasterMuscleIndexes();
|
||||
|
||||
if (disconnectMuscleFlags.Length != muscles.Length)
|
||||
{
|
||||
Array.Resize(ref disconnectMuscleFlags, muscles.Length);
|
||||
Array.Resize(ref muscleDisconnectModes, muscles.Length);
|
||||
Array.Resize(ref disconnectDeactivateFlags, muscles.Length);
|
||||
Array.Resize(ref reconnectMuscleFlags, muscles.Length);
|
||||
}
|
||||
|
||||
propMuscles = GetComponentsInChildren<PropMuscle>();
|
||||
|
||||
hasProp = HasProp();
|
||||
|
||||
if (OnHierarchyChanged != null) OnHierarchyChanged();
|
||||
}
|
||||
|
||||
// Checks if the puppet has a Prop attached
|
||||
private bool HasProp() {
|
||||
foreach (Muscle m in muscles) if (m.props.group == Muscle.Group.Prop) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Updates MuscleCollisionBroadcaster muscle indexes whenever the hierarchy changes
|
||||
private void UpdateBroadcasterMuscleIndexes() {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].broadcaster != null) muscles[i].broadcaster.muscleIndex = i;
|
||||
if (muscles[i].jointBreakBroadcaster != null) muscles[i].jointBreakBroadcaster.muscleIndex = i;
|
||||
}
|
||||
}
|
||||
|
||||
// Find parent and child muscle indexes for each muscle
|
||||
private void AssignParentAndChildIndexes() {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
// Parents
|
||||
muscles[i].parentIndexes = new int[0];
|
||||
|
||||
if (muscles[i].joint.connectedBody != null) {
|
||||
AddToParentsRecursive(muscles[i].joint.connectedBody.GetComponent<ConfigurableJoint>(), ref muscles[i].parentIndexes);
|
||||
}
|
||||
|
||||
// Children
|
||||
muscles[i].childIndexes = new int[0];
|
||||
muscles[i].childFlags = new bool[muscles.Length];
|
||||
|
||||
for (int n = 0; n < muscles.Length; n++) {
|
||||
if (i != n && muscles[n].joint.connectedBody == muscles[i].rigidbody) {
|
||||
AddToChildrenRecursive(muscles[n].joint, ref muscles[i].childIndexes, ref muscles[i].childFlags);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add all parent indexes to the indexes array recursively
|
||||
private void AddToParentsRecursive(ConfigurableJoint joint, ref int[] indexes) {
|
||||
if (joint == null) return;
|
||||
|
||||
int muscleIndex = GetMuscleIndexLowLevel(joint);
|
||||
if (muscleIndex == -1) return;
|
||||
|
||||
Array.Resize(ref indexes, indexes.Length + 1);
|
||||
indexes[indexes.Length - 1] = muscleIndex;
|
||||
|
||||
if (joint.connectedBody == null) return;
|
||||
AddToParentsRecursive(joint.connectedBody.GetComponent<ConfigurableJoint>(), ref indexes);
|
||||
}
|
||||
|
||||
// Add all child indexes to the indexes array recursively
|
||||
private void AddToChildrenRecursive(ConfigurableJoint joint, ref int[] indexes, ref bool[] childFlags) {
|
||||
if (joint == null) return;
|
||||
|
||||
int muscleIndex = GetMuscleIndexLowLevel(joint);
|
||||
if (muscleIndex == -1) return;
|
||||
|
||||
Array.Resize(ref indexes, indexes.Length + 1);
|
||||
indexes[indexes.Length - 1] = muscleIndex;
|
||||
|
||||
childFlags[muscleIndex] = true;
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (i != muscleIndex && muscles[i].joint.connectedBody == joint.GetComponent<Rigidbody>()) {
|
||||
AddToChildrenRecursive(muscles[i].joint, ref indexes, ref childFlags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AssignKinshipDegrees() {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
// Parents
|
||||
muscles[i].kinshipDegrees = new int[muscles.Length];
|
||||
|
||||
AssignKinshipsDownRecursive(ref muscles[i].kinshipDegrees, 1, i);
|
||||
AssignKinshipsUpRecursive(ref muscles[i].kinshipDegrees, 1, i);
|
||||
}
|
||||
}
|
||||
|
||||
private void AssignKinshipsDownRecursive(ref int[] kinshipDegrees, int degree, int index) {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (i != index) {
|
||||
if (muscles[i].joint.connectedBody == muscles[index].rigidbody) {
|
||||
kinshipDegrees[i] = degree;
|
||||
|
||||
AssignKinshipsDownRecursive(ref kinshipDegrees, degree + 1, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void AssignKinshipsUpRecursive(ref int[] kinshipDegrees, int degree, int index) {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (i != index) {
|
||||
if (muscles[i].rigidbody == muscles[index].joint.connectedBody) {
|
||||
kinshipDegrees[i] = degree;
|
||||
|
||||
AssignKinshipsUpRecursive(ref kinshipDegrees, degree + 1, i);
|
||||
|
||||
for (int c = 0; c < muscles.Length; c++) {
|
||||
if (c != i && c != index) {
|
||||
if (muscles[c].joint.connectedBody == muscles[i].rigidbody) {
|
||||
kinshipDegrees[c] = degree + 1;
|
||||
|
||||
AssignKinshipsDownRecursive(ref kinshipDegrees, degree + 2, c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the index of the muscle that has the specified Joint. Returns -1 if not found.
|
||||
private int GetMuscleIndexLowLevel(ConfigurableJoint joint) {
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i].joint == joint) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c088fb43c7fa040fdb96ac4e2e2c78f2
|
||||
timeCreated: 1436432414
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,133 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
public static class PuppetMasterTools {
|
||||
|
||||
public static void PositionRagdoll(PuppetMaster puppetMaster) {
|
||||
Rigidbody[] rigidbodies = puppetMaster.transform.GetComponentsInChildren<Rigidbody>();
|
||||
if (rigidbodies.Length == 0) return;
|
||||
|
||||
foreach (Muscle m in puppetMaster.muscles) if (m.joint == null || m.target == null) return;
|
||||
|
||||
Vector3[] swingAxes = new Vector3[rigidbodies.Length];
|
||||
|
||||
for (int i = 0; i < rigidbodies.Length; i++) {
|
||||
if (rigidbodies[i].transform.childCount == 1) {
|
||||
swingAxes[i] = rigidbodies[i].transform.InverseTransformDirection(rigidbodies[i].transform.GetChild(0).position - rigidbodies[i].transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Rigidbody r in rigidbodies) {
|
||||
foreach (Muscle m in puppetMaster.muscles) {
|
||||
if (m.joint.GetComponent<Rigidbody>() == r) {
|
||||
r.transform.position = m.target.position;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < rigidbodies.Length; i++) {
|
||||
if (rigidbodies[i].transform.childCount == 1) {
|
||||
Vector3 childPosition = rigidbodies[i].transform.GetChild(0).position;
|
||||
|
||||
rigidbodies[i].transform.rotation = Quaternion.FromToRotation(rigidbodies[i].transform.rotation * swingAxes[i], childPosition - rigidbodies[i].transform.position) * rigidbodies[i].transform.rotation;
|
||||
rigidbodies[i].transform.GetChild(0).position = childPosition;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void RealignRagdoll(PuppetMaster puppetMaster) {
|
||||
foreach (Muscle m in puppetMaster.muscles) {
|
||||
if (m.joint == null || m.joint.transform == null || m.target == null) {
|
||||
Debug.LogWarning("Muscles incomplete, can not realign ragdoll.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Muscle m in puppetMaster.muscles) {
|
||||
if (m.target != null) {
|
||||
Transform[] children = new Transform[m.joint.transform.childCount];
|
||||
for (int c = 0 ; c < children.Length; c++) {
|
||||
children[c] = m.joint.transform.GetChild(c);
|
||||
}
|
||||
|
||||
foreach (Transform c in children) c.parent = null;
|
||||
|
||||
BoxCollider box = m.joint.GetComponent<BoxCollider>();
|
||||
Vector3 boxSizeWorldSpace = Vector3.zero;
|
||||
Vector3 boxCenterWorldSpace = Vector3.zero;
|
||||
|
||||
if (box != null) {
|
||||
boxSizeWorldSpace = box.transform.TransformVector(box.size);
|
||||
boxCenterWorldSpace = box.transform.TransformVector(box.center);
|
||||
}
|
||||
|
||||
CapsuleCollider capsule = m.joint.GetComponent<CapsuleCollider>();
|
||||
Vector3 capsuleCenterWorldSpace = Vector3.zero;
|
||||
Vector3 capsuleDirectionWorldSpace = Vector3.zero;
|
||||
|
||||
if (capsule != null) {
|
||||
capsuleCenterWorldSpace = capsule.transform.TransformVector(capsule.center);
|
||||
capsuleDirectionWorldSpace = capsule.transform.TransformVector(DirectionIntToVector3(capsule.direction));
|
||||
}
|
||||
|
||||
SphereCollider sphere = m.joint.GetComponent<SphereCollider>();
|
||||
Vector3 sphereCenterWorldSpace = Vector3.zero;
|
||||
|
||||
if (sphere != null) {
|
||||
sphereCenterWorldSpace = sphere.transform.TransformVector(sphere.center);
|
||||
}
|
||||
|
||||
Vector3 jointAxisWorldSpace = m.joint.transform.TransformVector(m.joint.axis);
|
||||
Vector3 jointSecondaryAxisWorldSpace = m.joint.transform.TransformVector(m.joint.secondaryAxis);
|
||||
|
||||
// Rotate the bone
|
||||
m.joint.transform.rotation = m.target.rotation;
|
||||
|
||||
if (box != null) {
|
||||
box.size = box.transform.InverseTransformVector(boxSizeWorldSpace);
|
||||
box.center = box.transform.InverseTransformVector(boxCenterWorldSpace);
|
||||
}
|
||||
|
||||
if (capsule != null) {
|
||||
capsule.center = capsule.transform.InverseTransformVector(capsuleCenterWorldSpace);
|
||||
Vector3 directionLocalSpace = capsule.transform.InverseTransformDirection(capsuleDirectionWorldSpace);
|
||||
capsule.direction = DirectionVector3ToInt(directionLocalSpace);
|
||||
}
|
||||
|
||||
if (sphere != null) {
|
||||
sphere.center = sphere.transform.InverseTransformVector(sphereCenterWorldSpace);
|
||||
}
|
||||
|
||||
m.joint.axis = m.joint.transform.InverseTransformVector(jointAxisWorldSpace);
|
||||
m.joint.secondaryAxis = m.joint.transform.InverseTransformVector(jointSecondaryAxisWorldSpace);
|
||||
|
||||
foreach (Transform c in children) c.parent = m.joint.transform;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Vector3 DirectionIntToVector3(int dir) {
|
||||
if (dir == 0) return Vector3.right;
|
||||
if (dir == 1) return Vector3.up;
|
||||
return Vector3.forward;
|
||||
}
|
||||
|
||||
private static int DirectionVector3ToInt(Vector3 dir) {
|
||||
float dotX = Vector3.Dot(dir, Vector3.right);
|
||||
float dotY = Vector3.Dot(dir, Vector3.up);
|
||||
float dotZ = Vector3.Dot(dir, Vector3.forward);
|
||||
|
||||
float absDotX = Mathf.Abs(dotX);
|
||||
float absDotY = Mathf.Abs(dotY);
|
||||
float absDotZ = Mathf.Abs(dotZ);
|
||||
|
||||
int rotatedDirection = 0;
|
||||
if (absDotY > absDotX && absDotY > absDotZ) rotatedDirection = 1;
|
||||
if (absDotZ > absDotX && absDotZ > absDotY) rotatedDirection = 2;
|
||||
return rotatedDirection;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 28c2232c2644b42e196aad270e1fbaba
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
@@ -0,0 +1,113 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
using System;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
// Code for making sure if the PuppetMaster setup is valid.
|
||||
public partial class PuppetMaster: MonoBehaviour {
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether this PuppetMaster instance is valid for initiation.
|
||||
/// </summary>
|
||||
public bool IsValid(bool log) {
|
||||
if (muscles == null) {
|
||||
if (log) Debug.LogError("PuppetMaster Muscles is null.", transform);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (muscles.Length == 0) {
|
||||
if (log) Debug.LogError("PuppetMaster has no muscles.", transform);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (muscles[i] == null) {
|
||||
if (log) Debug.LogError("Muscle is null, PuppetMaster muscle setup is invalid.", transform);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!muscles[i].IsValid(log)) return false;
|
||||
}
|
||||
|
||||
if (targetRoot == null) {
|
||||
if (log) Debug.LogError("'Target Root' of PuppetMaster is null.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (targetRoot.position != transform.position) {
|
||||
if (log) Debug.LogError("The position of the animated character (Target) must match with the position of the PuppetMaster when initiating PuppetMaster. If you are creating the Puppet in runtime, make sure you don't move the Target to another position immediatelly after instantiation. Move the Root Transform instead.");
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
if (targetRoot.root != transform.root) {
|
||||
if (log) Debug.LogWarning("Target Root is not parented to the same root Transform as the PuppetMaster.", transform);
|
||||
return false;
|
||||
}
|
||||
*/
|
||||
|
||||
if (targetRoot == null) {
|
||||
if (log) Debug.LogError("Invalid PuppetMaster setup. (targetRoot not found)", transform);
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
for (int c = 0; c < muscles.Length; c++) {
|
||||
if (i != c) {
|
||||
if (muscles[i] == muscles[c] || muscles[i].joint == muscles[c].joint) {
|
||||
if (log) Debug.LogError("Joint " + muscles[i].joint.name + " is used by multiple muscles (indexes " + i + " and " + c + "), PuppetMaster muscle setup is invalid.", transform);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (muscles[0].joint.connectedBody != null && muscles.Length > 1) {
|
||||
for (int i = 1; i < muscles.Length; i++) {
|
||||
if (muscles[i].joint.GetComponent<Rigidbody>() == muscles[0].joint.connectedBody) {
|
||||
if (log) Debug.LogError("The first muscle needs to be the one that all the others are connected to (the hips).", transform);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
if (Vector3.SqrMagnitude(muscles[i].joint.transform.position - muscles[i].target.position) > 0.001f) {
|
||||
if (log) Debug.LogError("The position of each muscle needs to match with the position of it's target. Muscle '" + muscles[i].joint.name + "' position does not match with it's target. Right-click on the PuppetMaster component's header and select 'Fix Muscle Positions' from the context menu.", muscles[i].joint.transform);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
CheckMassVariation(100f, true);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Logs a warning if mass variation between the Rigidbodies in the ragdoll is more than 10 times.
|
||||
private bool CheckMassVariation(float threshold, bool log) {
|
||||
float minMass = Mathf.Infinity;
|
||||
float maxMass = 0f;
|
||||
for (int i = 0; i < muscles.Length; i++) {
|
||||
float mass = muscles[i].joint.GetComponent<Rigidbody>().mass;
|
||||
if (mass < minMass) minMass = mass;
|
||||
if (mass > maxMass) maxMass = mass;
|
||||
}
|
||||
|
||||
if (maxMass / minMass > threshold) {
|
||||
if (log) {
|
||||
Debug.LogWarning("Mass variation between the Rigidbodies in the ragdoll is more than " + threshold.ToString() + " times. This might cause instability and unwanted results with Rigidbodies connected by Joints. Min mass: " + minMass + ", max mass: " + maxMass, transform);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Log an error if API is called before initiation.
|
||||
private bool CheckIfInitiated() {
|
||||
if (!initiated) Debug.LogError("PuppetMaster has not been initiated yet.");
|
||||
return initiated;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2eb1c8b51338741fb8ae342c61ce0ab2
|
||||
timeCreated: 1436433546
|
||||
licenseType: Store
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,66 @@
|
||||
using UnityEngine;
|
||||
using System.Collections;
|
||||
|
||||
namespace RootMotion.Dynamics {
|
||||
|
||||
/// <summary>
|
||||
/// A floating point value that can be used as a simple float or a weight curve evaluated by another floating point parameter.
|
||||
/// </summary>
|
||||
[System.Serializable]
|
||||
public class Weight {
|
||||
|
||||
/// <summary>
|
||||
/// Simple float value or a curve evaluated by another floating point parameter.
|
||||
/// </summary>
|
||||
[System.Serializable]
|
||||
public enum Mode {
|
||||
Float,
|
||||
Curve
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Simple float value or a curve evaluated by another floating point parameter.
|
||||
/// </summary>
|
||||
public Mode mode;
|
||||
|
||||
/// <summary>
|
||||
/// The float value.
|
||||
/// </summary>
|
||||
public float floatValue;
|
||||
|
||||
/// <summary>
|
||||
/// The AnimationCurve.
|
||||
/// </summary>
|
||||
public AnimationCurve curve;
|
||||
|
||||
// A workaround for adding tooltips to custom property drawers.
|
||||
public string tooltip = "";
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RootMotion.Dynamics.Weight"/> class.
|
||||
/// </summary>
|
||||
public Weight(float floatValue) {
|
||||
this.floatValue = floatValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RootMotion.Dynamics.Weight"/> class.
|
||||
/// </summary>
|
||||
/// <param name="floatValue">Float value.</param>
|
||||
/// <param name="tooltip">Editor tooltip for this Weight.</param>
|
||||
public Weight(float floatValue, string tooltip) {
|
||||
this.floatValue = floatValue;
|
||||
this.tooltip = tooltip;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the value. If in 'Float' mode, will return floatValue, if 'Curve' mode, will return the curve's value evaluated at 'param'.
|
||||
/// </summary>
|
||||
public float GetValue(float param) {
|
||||
switch(mode) {
|
||||
case Mode.Curve: return curve.Evaluate(param);
|
||||
default: return floatValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 07e716c1af9804cc4baab95b54027a5c
|
||||
MonoImporter:
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
Reference in New Issue
Block a user