Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Bug Script to point object in camera direction inverts itself when at a random direction

Discussion in 'Scripting' started by JoeMamaLuigi, Dec 27, 2022.

  1. JoeMamaLuigi

    JoeMamaLuigi

    Joined:
    Oct 10, 2021
    Posts:
    2
    When using this code, everything seems to be working fine, until I point the camera in an oddly specific direction, (around -164 to -124 on y axis) inverting the x axis until I'm out of that area. This is in Unity 3D, and I have no idea what could be causing this problem.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class cameradirection : MonoBehaviour
    6. {
    7.     public GameObject fpsCam;
    8.     public GameObject gun;
    9.  
    10.     void Update()
    11.     {
    12.         gun.transform.localRotation = Quaternion.Euler(fpsCam.transform.localRotation.x * 200f, 0f, 0f);
    13.     }
    14. }
    15.  
    I'm making a third person game, but I basically just modified the Brackeys FPS engine so that it's in third person, adding Cinemachine to it.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,954
    Do not manipulate or interact with the .x, .y, .z or .w values of a Quaternion unless you have a math degree.

    These properties are NOT degrees and they are NOT radians. They are NOT useful to you.

    And you should CERTAINLY never be scaling it by 200f!

    Are you perhaps looking for
    localRotation.eulerAngles.x
    ?

    Even that is going to have potential rotational issues, so I'm not sure what you're after here.

    All about Euler angles and rotations, by StarManta:

    https://starmanta.gitbooks.io/unitytipsredux/content/second-question.html
     
    JoeMamaLuigi likes this.
  3. TzuriTeshuba

    TzuriTeshuba

    Joined:
    Aug 6, 2019
    Posts:
    185
    A couple issues i notice:
    1) you use fps.transform.localRotation.x. Notice that the 'localRotation' is a Quaternion and NOT a Vector3. its value is fairly meaningless outside of quaternion calculations. It does NOT represent the rotation about the x-axis as you might expect. Did you mean fpsCam.transform.localEulerAngles.x?

    2) that being said, the localEulerAngles may work for your case, but I refrain from using it unless I am certain of some invariant conditions. If the localEulerAngles doesn't work for you, consider just measuring the angle you are interested in with Vector3.Angle()
     
    JoeMamaLuigi and Kurt-Dekker like this.
  4. JoeMamaLuigi

    JoeMamaLuigi

    Joined:
    Oct 10, 2021
    Posts:
    2
    Both of these worked perfectly, thank you.