yu00’s blog

プログラミングに関する備忘録です

Unityで高度計を作る

はじめに

Unityで飛行機のコックピット風の高度計を作る方法を説明します

考え方

高度20mをステップ0、高度25mをステップ1のように
高度をステップで表します。
求めるのはキャンバス0地点から現在のステップまでのステップ
transStepです。

  • presentStep : 現在のステップ
  • presentPos : 現在のステップの高度
  • pos : 現在高度
  • transStep : キャンバス0地点から現在のステップまでのステップ
  • transPos : キャンバス0地点から現在のステップまでの高度
  • stepPos : 1ステップの高度

コード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Altimeter : MonoBehaviour
{
    public float StepPos;
    public float PosToCanvasUnit;
    public AltimeterNeedle[] Needles;
    public Rigidbody CharacterRigidbody;

    private void Update()
    {
        float pos = CharacterRigidbody.transform.position.y;
        for (int i = 0; i < Needles.Length; i++)
        {
            float transStep = GetTranslationStep(pos, StepPos, i - Needles.Length / 2);
            AltimeterNeedle needle = Needles[i];
            needle.transform.position = transform.position;
            needle.transform.Translate(0, transStep * PosToCanvasUnit, 0);
            string num = ((int)Mathf.Abs(pos / StepPos) + i).ToString("00");
            needle.Texts[0].text = num;
            needle.Texts[1].text = num;
        }
    }
    private float GetTranslationStep(float pos, float stepPos, int presentStep)
    {
        float presentPos = stepPos * (int)(pos / stepPos);
        float diffPos = presentPos - pos;
        float transPos = diffPos + stepPos * presentStep;
        return transPos / stepPos;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AltimeterNeedle : MonoBehaviour
{
    public Text[] Texts;
}

Unityプロジェクトは以下にあります。
https://github.com/hide00310/Unity_Altimeter