Skip to content

Instantly share code, notes, and snippets.

@SnugglePilot
Created September 21, 2016 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SnugglePilot/489d821ec9b01bbb1ef93cab737c768b to your computer and use it in GitHub Desktop.
Save SnugglePilot/489d821ec9b01bbb1ef93cab737c768b to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class SmoothDampTransform : MonoBehaviour {
public bool trackPosition = true;
public bool trackRotation = true;
public float translateTime;
public float rotateTime;
public Vector3 targetPosition { get; private set; }
public Quaternion targetRotation { get; private set; }
private Vector3 moveVel = Vector3.zero;
private Vector3 rotVel = Vector3.zero;
private float posTrackingTimeLeft;
private float rotTrackingTimeLeft;
void Start() {
targetPosition = transform.position;
targetRotation = transform.rotation;
}
public void SmoothTo(Transform t) {
SmoothTo (t.position, t.rotation);
}
public void SmoothTo(Vector3 position, Quaternion rotation) {
SmoothTo (position);
SmoothTo (rotation);
}
public void SmoothTo(Quaternion rotation) {
rotTrackingTimeLeft = rotateTime;
targetRotation = rotation;
}
public void SmoothTo(Vector3 position) {
posTrackingTimeLeft = translateTime;
targetPosition = position;
}
void Update () {
if (trackPosition && posTrackingTimeLeft > 0) {
posTrackingTimeLeft -= Time.deltaTime;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref moveVel, translateTime, Mathf.Infinity, Time.deltaTime);
}
if (trackRotation && rotTrackingTimeLeft > 0) {
rotTrackingTimeLeft -= Time.deltaTime;
Vector3 eulerAngles = this.transform.rotation.eulerAngles;
eulerAngles.x = Mathf.SmoothDampAngle(eulerAngles.x, targetRotation.eulerAngles.x, ref rotVel.x, rotateTime, Mathf.Infinity, Time.deltaTime);
eulerAngles.y = Mathf.SmoothDampAngle(eulerAngles.y, targetRotation.eulerAngles.y, ref rotVel.y, rotateTime, Mathf.Infinity, Time.deltaTime);
eulerAngles.z = Mathf.SmoothDampAngle(eulerAngles.z, targetRotation.eulerAngles.z, ref rotVel.z, rotateTime, Mathf.Infinity, Time.deltaTime);
if (float.IsNaN(eulerAngles.x) || float.IsNaN (eulerAngles.y) || float.IsNaN (eulerAngles.z)) {
// Woops. I don't know why this is the case. TODO: Find out why and fix later.
//Debug.Log ("1:"+this.transform.rotation.eulerAngles);
//Debug.Log ("2:"+targetRotation.eulerAngles);
// ^^ Always the same?!
} else {
this.transform.rotation = Quaternion.Euler (eulerAngles);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment