Last active
April 7, 2017 10:58
-
-
Save samsamm777/4213a82c09b3785a689bfe0fef208d97 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; | |
using System.Collections; | |
public class Looky : MonoBehaviour | |
{ | |
/** | |
* The target we will snap to. | |
*/ | |
public Transform target; | |
/** | |
* The child socket transforms | |
*/ | |
private Transform[] sockets; | |
/** | |
* Indicates which socket we are using. | |
* @type {Number} | |
*/ | |
public int index = 0; | |
void Start() | |
{ | |
sockets = GetComponentsInChildren<Transform>(); | |
} | |
/** | |
* Rotates the cube so that the chosen socket is orientated toward the target | |
* transform. | |
*/ | |
void Update () | |
{ | |
if (sockets[index] != null) | |
{ | |
// this is the local direction to the socket | |
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, sockets[index].transform.localPosition); | |
// look at the forward direction and also rotate with the extra socket rotation | |
Quaternion lookRotation = Quaternion.LookRotation(-target.forward, transform.up) * rot; | |
// slerp the transform rotation | |
transform.rotation = lookRotation; | |
Vector3 offset = transform.position - sockets[index].transform.position; | |
// position! | |
transform.position = target.position - (target.forward * offset.magnitude); | |
} | |
} | |
void OnDrawGizmos() | |
{ | |
if (sockets != null && sockets.Length > 0) { | |
Gizmos.color = Color.green; | |
Gizmos.DrawLine(transform.position, sockets[index].transform.position); | |
} | |
if (target != null) { | |
Gizmos.DrawLine(target.position, target.position - target.forward * 2f); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment