Skip to content

Instantly share code, notes, and snippets.

@petfactory
Created April 18, 2016 19:07
Show Gist options
  • Save petfactory/713aa19a0747b138476ac2ec7a922a8e to your computer and use it in GitHub Desktop.
Save petfactory/713aa19a0747b138476ac2ec7a922a8e to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class RotateCar : MonoBehaviour {
public GameObject car;
public GameObject doorLeft;
public GameObject doorRight;
private float rotateInc = 45.0f;
private Quaternion destRotation;
private Quaternion leftDoorOpenQuat = Quaternion.Euler(270, 237, 0);
private Quaternion leftDoorClosedQuat;
private Quaternion rightDoorOpenQuat = Quaternion.Euler(90, -60, 0);
private Quaternion rightDoorClosedQuat;
private float smoothing = 7f;
private bool leftDoorOpen = false;
private bool rightDoorOpen = false;
private Quaternion doorLeftClosed;
private Quaternion doorRightClosed;
private IEnumerator carCoroutine;
private IEnumerator leftDoorCoroutine;
private IEnumerator rightDoorCoroutine;
// Use this for initialization
void Start () {
leftDoorClosedQuat = doorLeft.transform.localRotation;
rightDoorClosedQuat = doorRight.transform.localRotation;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Space)) {
destRotation = Quaternion.Euler(0, destRotation.eulerAngles.y+rotateInc, 0);
if (carCoroutine != null) StopCoroutine(carCoroutine);
carCoroutine = rotateTo(car.transform, destRotation);
StartCoroutine(carCoroutine);
}
if(Input.GetKeyDown(KeyCode.LeftArrow)) {
if (!leftDoorOpen) {
if (leftDoorCoroutine != null) StopCoroutine(leftDoorCoroutine);
leftDoorCoroutine = rotateTo(doorLeft.transform, leftDoorOpenQuat);
StartCoroutine(leftDoorCoroutine);
leftDoorOpen = true;
} else {
if (leftDoorCoroutine != null) StopCoroutine(leftDoorCoroutine);
leftDoorCoroutine = rotateTo(doorLeft.transform, leftDoorClosedQuat);
StartCoroutine(leftDoorCoroutine);
leftDoorOpen = false;
}
}
if(Input.GetKeyDown(KeyCode.RightArrow)) {
if (!rightDoorOpen) {
if (rightDoorCoroutine != null) StopCoroutine(rightDoorCoroutine);
rightDoorCoroutine = rotateTo(doorRight.transform, rightDoorOpenQuat);
StartCoroutine(rightDoorCoroutine);
rightDoorOpen = true;
} else {
if (rightDoorCoroutine != null) StopCoroutine(rightDoorCoroutine);
rightDoorCoroutine = rotateTo(doorRight.transform, rightDoorClosedQuat);
StartCoroutine(rightDoorCoroutine);
rightDoorOpen = false;
}
}
}
IEnumerator rotateTo (Transform transform, Quaternion destRotation)
{
while(Quaternion.Angle(transform.localRotation, destRotation) > 0.1f)
{
transform.localRotation = Quaternion.Slerp(transform.localRotation, destRotation, smoothing * Time.deltaTime);
yield return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment