67 lines
2.8 KiB
C#

using UnityEngine;
namespace CreatureControl {
/// <summary>
/// A target rig or skeleton for a creature
/// </summary>
public class TargetRig : MonoBehaviour {
/// <summary>
/// Pose the target rig using the IK targets
/// </summary>
public virtual void Pose() {
}
/// <summary>
/// Align the target rig with a creature
/// </summary>
/// <param name="creature">The creature to align to</param>
public void MatchTo(Creature creature) {
bool anythingChangedDummy = false;
MatchTo(creature, ref anythingChangedDummy);
}
/// <summary>
/// Align the target rig with a creature
/// </summary>
/// <param name="creature">The creature to align to</param>
/// <param name="anythingChanged">True when any property of the creature has changed</param>
public virtual void MatchTo(Creature creature, ref bool anythingChanged) {
if (creature == null || creature.model == null)
return;
Vector3 targetToModelTranslation = creature.model.position - this.transform.position;
bool changed = targetToModelTranslation != creature.targetToModelTranslation;
if (changed) {
anythingChanged = true;
creature.targetToModelTranslation = targetToModelTranslation;
}
Quaternion targetToModelRotation = Quaternion.Inverse(this.transform.rotation) * creature.model.rotation;
changed = targetToModelRotation != creature.targetToModelRotation;
if (changed) {
anythingChanged = true;
creature.targetToModelRotation = targetToModelRotation;
}
}
/// <summary>
/// Compute the rotation from the target bone to a creature's bone
/// </summary>
/// <param name="bone">The creature's bone for this target bone</param>
/// <param name="nextBone">The next bone in the creature's hierarchy</param>
/// <returns>The rotation from the target bone rotation to the creature bone rotation</returns>
/// The next bone is used to compute the direction of the bone.
/// The 'up'-direction of the bone is currently fixed to (world) up.
public static Quaternion TargetToBoneRotation(Transform bone, Transform nextBone) {
if (bone == null || nextBone == null)
return Quaternion.identity;
Vector3 direction = nextBone.position - bone.position;
Quaternion targetRotation = Quaternion.LookRotation(direction, Vector3.up);
Quaternion toBoneRotation = Quaternion.Inverse(targetRotation) * bone.rotation;
return toBoneRotation;
}
}
}