Created
September 3, 2021 07:19
-
-
Save alankent/0d8bf757a8e9e3c34a5c8b525da84858 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[ExecuteAlways] | |
public class TrackObjects : MonoBehaviour | |
{ | |
public Transform target1; | |
[Range(0f, 1f)] public float target1Weight; | |
public Transform target2; | |
[Range(0f, 1f)] public float target2Weight; | |
public Transform target3; | |
[Range(0f, 1f)] public float target3Weight; | |
public void LateUpdate() | |
{ | |
Recompute(); | |
} | |
bool Recompute() | |
{ | |
if (target1 == null) target1Weight = 0; | |
if (target2 == null) target2Weight = 0; | |
if (target3 == null) target3Weight = 0; | |
int count = 0; | |
if (target1Weight > 0f) count++; | |
if (target2Weight > 0f) count++; | |
if (target3Weight > 0f) count++; | |
if (count == 0) | |
{ | |
return false; | |
} | |
// Work out the target point based on the relative weights for the targets. | |
float totalWeight = target1Weight + target2Weight + target3Weight; | |
Vector3 averagePosition = Vector3.zero; | |
// based on [URL='https://forum.unity.com/members/lordofduct.66428/']lordofduct[/URL] response | |
Quaternion averageRotation = Quaternion.identity; | |
if (target1 != null && target1Weight > 0f) | |
{ | |
averagePosition += target1.position * (target1Weight / totalWeight); | |
averageRotation *= Quaternion.Slerp(Quaternion.identity, target1.rotation, target1Weight / totalWeight); | |
} | |
if (target2 != null && target2Weight > 0f) | |
{ | |
averagePosition += target2.position * (target2Weight / totalWeight); | |
averageRotation *= Quaternion.Slerp(Quaternion.identity, target2.rotation, target2Weight / totalWeight); | |
} | |
if (target3 != null && target3Weight > 0f) | |
{ | |
averagePosition += target3.position * (target3Weight / totalWeight); | |
averageRotation *= Quaternion.Slerp(Quaternion.identity, target3.rotation, target3Weight / totalWeight); | |
} | |
this.transform.position = averagePosition; | |
this.transform.rotation = averageRotation; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment