Skip to content

Instantly share code, notes, and snippets.

@samsamm777
Last active July 8, 2016 12:36
Show Gist options
  • Save samsamm777/b91648b86b9d1de0ca5a8cc919f67ea0 to your computer and use it in GitHub Desktop.
Save samsamm777/b91648b86b9d1de0ca5a8cc919f67ea0 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class Looky : MonoBehaviour
{
/**
* The target for where we want to face
*/
public Transform target;
/**
* The child socket transforms
*/
public Transform[] sockets;
/**
* Indicates which socket we are using.
* @type {Number}
*/
public int index = 0;
/**
* The speed in which the rotation will occur over time.
*/
public float rotationSpeed;
/**
* Rotates the cube so that the chosen socket is orientated toward the target
* transform.
*/
void Update ()
{
// Draw some debug lines to each socket.
for(int i = 0; i < sockets.Length; i++)
{
Debug.DrawLine(transform.position, sockets[i].transform.position, Color.green);
}
if (sockets[index] != null)
{
// This is the forward vector
Vector3 forward = target.transform.position - transform.position;
// this is the local direction to the socket
Vector3 dir = sockets[index].transform.localPosition - Vector3.zero;
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, -dir);
// look at the forward direction and also rotate with the extra socket rotation
Quaternion lookRotation = Quaternion.LookRotation(forward) * rot;
// slerp the transform rotation
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * rotationSpeed);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment