Created
August 4, 2019 16:50
-
-
Save ciwolsey/394c38fa5d2390fdb5a8a1584ef211ce to your computer and use it in GitHub Desktop.
This file contains 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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
namespace Interakt.Components.Constraints { | |
public class ConstrainRotationAxis : MonoBehaviour | |
{ | |
public enum ConstraintSpace { | |
Local, | |
World | |
} | |
public ConstraintSpace Space; | |
public bool LockX, LockY, LockZ; | |
private Vector3 OriginalRotation; | |
private Vector3 NextRotation; | |
void Awake() | |
{ | |
// Store the original rotation of this gameobject | |
OriginalRotation = Space == ConstraintSpace.Local ? transform.localEulerAngles : transform.eulerAngles; | |
} | |
void LateUpdate() | |
{ | |
// Constrained rotation is initially the same as the transform position | |
NextRotation = Space == ConstraintSpace.Local ? transform.localEulerAngles : transform.eulerAngles; | |
// Constrain if required | |
if(LockX) | |
RevertX(ref NextRotation); | |
if(LockY) | |
RevertY(ref NextRotation); | |
if(LockZ) | |
RevertZ(ref NextRotation); | |
if(Space == ConstraintSpace.Local) | |
{ | |
transform.localEulerAngles = NextRotation; | |
} else { | |
transform.eulerAngles = NextRotation; | |
} | |
} | |
void RevertX(ref Vector3 rot) | |
{ | |
rot.x = OriginalRotation.x; | |
} | |
void RevertY(ref Vector3 rot) | |
{ | |
rot.y = OriginalRotation.y; | |
} | |
void RevertZ(ref Vector3 rot) | |
{ | |
rot.z = OriginalRotation.z; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment