Search Unity

Dealing with Gimble lock

Discussion in 'Scripting' started by official_hype, Aug 30, 2015.

  1. official_hype

    official_hype

    Joined:
    Aug 30, 2015
    Posts:
    1
    Hello! I have the object powered by physics. Object moves along the XZ plane. I'm writing a script for camera to follow this object, so camera stays at the specific point relative to object position and rotation (actually "behind" the object).
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. public class FollowCam : MonoBehaviour {
    4.     public GameObject target;
    5.     public float camDistance;
    6.     private Vector3 camPos;
    7.     public float camHeight;
    8.  
    9. void LateUpdate() {
    10.         float angle = (target.transform.rotation.eulerAngles.y * Mathf.Deg2Rad);
    11.         float x = Mathf.Sin (angle);
    12.         float z = Mathf.Cos (angle);
    13.         camPos = new Vector3 (x, camHeight, z);
    14.         camPos = camPos * -camDistance;
    15.         transform.position = new Vector3 (camPos.x + target.transform.position.x,camHeight,camPos.z + target.transform.position.z);
    16.         transform.LookAt(target.transform,Vector3.up);
    17.  
    18.         }
    19.     }
    The problem I have is then object rotates more than 90 or 270 degrees along X axis, Im getting "opposite" camera position. ("in front of the obj")
    I see two options to deal with this problem:
    1) Use quatrernions, but since my script based on angle along Y axis i need to get this from quaternion. Can I do that?
    2) Tracking angle change and changeng the sign of camPos vector in line 14, but things like
    Code (CSharp):
    1. if (angle >= 270 || angle<= 90)
    2. {sign *=-1;}
    doesnt seem to work.
     
    Last edited: Aug 30, 2015