[Help] Speedometer angle problem

Hi everybody ,

I try to create a 3d speedometer but i have a little problem :frowning:

my needle for the km/h start rotation at 0 on z axis and finish at -278 on z axis.
and with my script the needle start to become crazy and turn on all axis :frowning: after 100km/h

here is the script :

using UnityEngine;
using System.Collections;
public class Speedometer : MonoBehaviour {
  
    public GameObject car;
    public RCC_CarControllerV3 carScript;
     //public GameObject RPMSpeedo;
     public GameObject KMHSpeedo;
     public int maxangleKMH;
     public int minangleKMH;
     public float angle;
     // Use this for initialization
     void Start () {
         maxangleKMH = 350;
         minangleKMH = 0;
     }
   
     // Update is called once per frame
     void Update () {
   
        carScript = car.GetComponent<RCC_CarControllerV3>();
        angle = Mathf.Clamp(carScript.speed / carScript.maxspeed * (maxangleKMH - minangleKMH) + minangleKMH, minangleKMH, maxangleKMH);
        KMHSpeedo.transform.localRotation = Quaternion.AngleAxis(-angle, KMHSpeedo.transform.forward);
     }
}

can you please help me guys ?

Thanks by advance .

In Line 23 you probably want something more like:

KMHSpeedo.transform.localRotation = Quaternion.Euler( 0, 0, angle);

to explicitly rotate it on the local Z axis. You might even want to just drive the .rotation field instead of .localRotation, but I’m not sure how you set up your scene.

If this doesn’t fix your problem, then most likely one of your needle objects or prefabs is not oriented at (0,0,0) when it comes into the scene (rotation-wise).

Make a blank GameObject that actually IS rotation (0,0,0) (this is called identity rotation, i.e., no rotation), and then put the needle as a child of that blank GameObject, and when you rotate, you rotate only the blank one, causing the children to rotate correctly.

If the needle prefab itself has transforms not at identity rotation, then you can remake the prefab with an additional identity-rotated GameObject as the new root of the prefab.

Either way, I would still recommend the above rotation code instead, because it is invariant with regards to the needle orientation.