add Physics support

This commit is contained in:
1605296300@qq.com
2022-08-10 16:54:20 +08:00
parent 33c8d35c84
commit f797fbb2fd
855 changed files with 649609 additions and 98 deletions
@@ -0,0 +1,126 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
[System.Serializable]
public class SubBehaviourBalancer : SubBehaviourBase {
/// <summary>
/// Settings for SubBehaviourBalancer.
/// </summary>
[System.Serializable]
public class Settings {
[Tooltip("Ankle joint damper / spring. Increase to make the balancing effect softer.")]
/// <summary>
/// Ankle joint damper / spring. Increase to make the balancing effect softer.
/// </summary>
public float damperForSpring = 1f;
[Tooltip("Multiplier for joint max force.")]
/// <summary>
/// Multiplier for joint max force.
/// </summary>
public float maxForceMlp = 0.05f;
[Tooltip("Multiplier for the inertia tensor. Increasing this will increase the balancing forces.")]
/// <summary>
/// Multiplier for the inertia tensor. Increasing this will increase the balancing forces.
/// </summary>
public float IMlp = 1f;
[Tooltip("Velocity-based prediction.")]
/// <summary>
/// Velocity-based prediction.
/// </summary>
public float velocityF = 0.5f;
[Tooltip("World space offset for the center of pressure. Can be used to make the characer lean in a certain direction.")]
/// <summary>
/// World space offset for the center of pressure. Can be used to make the characer lean in a certain direction.
/// </summary>
public Vector3 copOffset;
[Tooltip("The amount of torque applied to the lower legs to help keep the puppet balanced. Note that this is an external force (not coming from the joints themselves) and might make the simulation seem unnatural.")]
/// <summary>
/// The amount of torque applied to the lower legs to help keep the puppet balanced. Note that this is an external force (not coming from the joints themselves) and might make the simulation seem unnatural.
/// </summary>
public float torqueMlp = 0f;
[Tooltip("Maximum magnitude of the torque applied to the lower legs if 'Torque Mlp' > 0.")]
/// <summary>
/// Maximum magnitude of the torque applied to the lower legs if 'Torque Mlp' > 0.
/// </summary>
public float maxTorqueMag = 45f;
}
public ConfigurableJoint joint { get; private set; }
public Vector3 dir { get; private set;}
public Vector3 dirVel { get; private set;}
public Vector3 cop { get; private set; }
public Vector3 com { get; private set; }
public Vector3 comV { get; private set; }
private Settings settings;
private Rigidbody[] rigidbodies = new Rigidbody[0];
private Transform[] copPoints = new Transform[0];
private PressureSensor pressureSensor;
private Rigidbody Ibody;
private Vector3 I;
private Quaternion toJointSpace = Quaternion.identity;
public void Initiate(BehaviourBase behaviour, Settings settings, Rigidbody Ibody, Rigidbody[] rigidbodies, ConfigurableJoint joint, Transform[] copPoints, PressureSensor pressureSensor) {
this.behaviour = behaviour;
this.settings = settings;
this.Ibody = Ibody;
this.rigidbodies = rigidbodies;
this.joint = joint;
this.copPoints = copPoints;
this.pressureSensor = pressureSensor;
toJointSpace = PhysXTools.ToJointSpace(joint);
behaviour.OnPreFixedUpdate += Solve;
}
void Solve() {
if (copPoints.Length == 0) {
cop = joint.transform.TransformPoint(joint.anchor);
} else {
cop = Vector3.zero;
foreach (Transform copPoint in copPoints) {
cop += copPoint.position;
}
cop /= copPoints.Length;
}
cop += settings.copOffset;
com = PhysXTools.GetCenterOfMass(rigidbodies);
comV = PhysXTools.GetCenterOfMassVelocity(rigidbodies);
dir = com - cop;
dirVel = (com + comV * settings.velocityF) - cop;
Vector3 requiredAcceleration = PhysXTools.GetFromToAcceleration(dirVel, -Physics.gravity);
requiredAcceleration -= Ibody.angularVelocity;
Vector3 torque = requiredAcceleration / Time.fixedDeltaTime;
PhysXTools.ScaleByInertia(ref torque, Ibody.rotation, Ibody.inertiaTensor * settings.IMlp);
torque = Vector3.ClampMagnitude(torque, settings.maxTorqueMag);
bool pressured = pressureSensor == null || !pressureSensor.enabled || pressureSensor.inContact;
if (pressured) {
Ibody.AddTorque(torque * settings.torqueMlp, ForceMode.Force);
joint.targetAngularVelocity = Quaternion.Inverse(toJointSpace) * Quaternion.Inverse(joint.transform.rotation) * torque;
} else {
joint.targetAngularVelocity = Vector3.zero;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 6de31dba92eea4c2492989c03b792b73
timeCreated: 1482328947
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
/// <summary>
/// The sub-behaviours take care of behaviour code reusability.
/// While there can be only one active Puppet Behaviour at a time, that active behaviour can use multiple independent and reusable sub-behaviours simultaneously.
/// For example the SubBehaviourCOM is responsible for calculating everything about the center of mass and can be used by any behaviour or even other sub-behaviours that need CoM calculations.
/// This is the base abstract class for all sub-behaviours.
/// </summary>
[System.Serializable]
public abstract class SubBehaviourBase {
protected BehaviourBase behaviour;
protected static Vector2 XZ(Vector3 v) {
return new Vector2(v.x, v.z);
}
protected static Vector3 XYZ(Vector2 v) {
return new Vector3(v.x, 0f, v.y);
}
protected static Vector3 Flatten(Vector3 v) {
return new Vector3(v.x, 0f, v.z);
}
protected static Vector3 SetY(Vector3 v, float y) {
return new Vector3(v.x, y, v.z);
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a3b383b7d9ca6498692219a366e82ab7
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
@@ -0,0 +1,222 @@
using UnityEngine;
using System.Collections;
namespace RootMotion.Dynamics {
[System.Serializable]
public class SubBehaviourCOM: SubBehaviourBase {
[System.Serializable]
public enum Mode {
FeetCentroid,
CenterOfPressure
}
public Mode mode;
public float velocityDamper = 1f;
public float velocityLerpSpeed = 5f;
public float velocityMax = 1f;
public float centerOfPressureSpeed = 5f;
public Vector3 offset;
public Vector3 position { get; private set; }
public Vector3 direction { get; private set; }
public float angle { get; private set; }
public Vector3 velocity { get; private set; }
public Vector3 centerOfPressure { get; private set; }
public Quaternion rotation { get; private set; }
public Quaternion inverseRotation { get; private set; }
public bool isGrounded { get; private set; }
public float lastGroundedTime { get; private set; }
[HideInInspector] public bool[] groundContacts;
[HideInInspector] public Vector3[] groundContactPoints;
private LayerMask groundLayers;
public void Initiate(BehaviourBase behaviour, LayerMask groundLayers) {
this.behaviour = behaviour;
this.groundLayers = groundLayers;
rotation = Quaternion.identity;
groundContacts = new bool[behaviour.puppetMaster.muscles.Length];
groundContactPoints = new Vector3[groundContacts.Length];
behaviour.OnPreActivate += OnPreActivate;
behaviour.OnPreLateUpdate += OnPreLateUpdate;
behaviour.OnPreDeactivate += OnPreDeactivate;
behaviour.OnPreMuscleCollision += OnPreMuscleCollision;
behaviour.OnPreMuscleCollisionExit += OnPreMuscleCollisionExit;
behaviour.OnHierarchyChanged += OnHierarchyChanged;
}
#region Behaviour Delegates
private void OnHierarchyChanged() {
System.Array.Resize (ref groundContacts, behaviour.puppetMaster.muscles.Length);
System.Array.Resize (ref groundContactPoints, behaviour.puppetMaster.muscles.Length);
}
private void OnPreMuscleCollision(MuscleCollision c) {
if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer)) return;
if (c.collision.contacts.Length == 0) return;
lastGroundedTime = Time.time;
groundContacts[c.muscleIndex] = true;
if (mode == Mode.CenterOfPressure) groundContactPoints[c.muscleIndex] = GetCollisionCOP(c.collision);
}
private void OnPreMuscleCollisionExit(MuscleCollision c) {
if (!LayerMaskExtensions.Contains(groundLayers, c.collision.gameObject.layer)) return;
groundContacts[c.muscleIndex] = false;
groundContactPoints[c.muscleIndex] = Vector3.zero;
}
private void OnPreActivate() {
position = GetCenterOfMass();
centerOfPressure = GetFeetCentroid();
direction = position - centerOfPressure;
angle = Vector3.Angle(direction, Vector3.up);
velocity = Vector3.zero;
}
private void OnPreLateUpdate() {
// Ground contact
isGrounded = IsGrounded();
// COP
if (mode == Mode.FeetCentroid || !isGrounded) {
centerOfPressure = GetFeetCentroid();
} else {
Vector3 centerOfPressureTarget = isGrounded? GetCenterOfPressure(): GetFeetCentroid();
centerOfPressure = centerOfPressureSpeed <= 02? centerOfPressureTarget: Vector3.Lerp(centerOfPressure, centerOfPressureTarget, Time.deltaTime * centerOfPressureSpeed);
}
// COM
position = GetCenterOfMass();
// COM Velocity
Vector3 velocityPosition = GetCenterOfMassVelocity();
Vector3 velocityTarget = velocityPosition - position;
velocityTarget.y = 0f;
velocityTarget = Vector3.ClampMagnitude(velocityTarget, velocityMax);
// Add velocity to position
velocity = velocityLerpSpeed <= 0f? velocityTarget: Vector3.Lerp(velocity, velocityTarget, Time.deltaTime * velocityLerpSpeed);
position += velocity * velocityDamper;
position += behaviour.puppetMaster.targetRoot.rotation * offset;
// Calculate COM direction, rotation and angle
direction = position - centerOfPressure;
rotation = Quaternion.FromToRotation(Vector3.up, direction);
inverseRotation = Quaternion.Inverse(rotation);
angle = Quaternion.Angle(Quaternion.identity, rotation);
}
private void OnPreDeactivate() {
velocity = Vector3.zero;
}
#endregion Behaviour Delegates
private Vector3 GetCollisionCOP(Collision collision) {
Vector3 sum = Vector3.zero;
for (int i = 0; i < collision.contacts.Length; i++) {
sum += collision.contacts[i].point;
}
return sum / (float)collision.contacts.Length;
}
private bool IsGrounded() {
for (int i = 0; i < groundContacts.Length; i++) {
if (groundContacts[i]) return true;
}
return false;
}
private Vector3 GetCenterOfMass() {
Vector3 CoM = Vector3.zero;
float c = 0f;
foreach (Muscle m in behaviour.puppetMaster.muscles) {
CoM += m.rigidbody.worldCenterOfMass * m.rigidbody.mass;
c += m.rigidbody.mass;
}
return CoM /= c;
}
private Vector3 GetCenterOfMassVelocity() {
Vector3 CoM = Vector3.zero;
float c = 0f;
foreach (Muscle m in behaviour.puppetMaster.muscles) {
CoM += m.rigidbody.worldCenterOfMass * m.rigidbody.mass;
CoM += m.rigidbody.velocity * m.rigidbody.mass;
c += m.rigidbody.mass;
}
return CoM /= c;
}
private Vector3 GetMomentum() {
Vector3 sum = Vector3.zero;
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.velocity * behaviour.puppetMaster.muscles[i].rigidbody.mass;
}
return sum;
}
private Vector3 GetCenterOfPressure() {
Vector3 sum = Vector3.zero;
int contacts = 0;
for (int i = 0; i < groundContacts.Length; i++) {
if (groundContacts[i]) {
sum += groundContactPoints[i];
contacts ++;
}
}
sum /= (float)contacts;
return sum;
}
private Vector3 GetFeetCentroid() {
Vector3 sum = Vector3.zero;
int contacts = 0;
/*
int feetGrounded = 0;
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot && groundContacts[i]) feetGrounded ++;
}
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot) {
if (feetGrounded == 0 || (feetGrounded > 0 && groundContacts[i])) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.worldCenterOfMass;
contacts ++;
}
}
}
*/
for (int i = 0; i < behaviour.puppetMaster.muscles.Length; i++) {
if (behaviour.puppetMaster.muscles[i].props.group == Muscle.Group.Foot) {
sum += behaviour.puppetMaster.muscles[i].rigidbody.worldCenterOfMass;
contacts ++;
}
}
sum /= (float)contacts;
return sum;
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0763c4b89286d49acaa9fdf15769756f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: