2019年9月3日 星期二

賽車儀錶板_簡易版

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

public class Canvas_Obj : MonoBehaviour
{
    private const float MAX_SPEED_ANGLE = -166;         // 儀錶板角度 (開始刻度)
    private const float ZERO_SPEED_ANGLE = 180;         // 儀錶板角度 (結束刻度)

    public RectTransform needleTranform;                // 儀錶板指針

    private float speedMax;
    private float speed;

    public float forward_Speed = 50;     // 加速儀錶板指針
    public float break_Speed = -100;    //  減速加入儀表板指針
    public float null_Speed = -20;      // 未加速儀表板指針

    void Awake()
    {
        speed = 0;  
        speedMax = 220f;
    }

    void Update()
    {
        HadlePlayerInput();
        needleTranform.eulerAngles = new Vector3(0, 0, GetSpeedRotation());       
    }  

    private void HadlePlayerInput()
    {
        float vertical = Input.GetAxis("Vertical");
        float pointerSpeed = (vertical > 0) ? pointerSpeed = forward_Speed : (vertical < 0) ? pointerSpeed = break_Speed : pointerSpeed = null_Speed;

        speed += pointerSpeed * Time.deltaTime;

        speed = Mathf.Clamp(speed, 0f, speedMax);
    }

    private float GetSpeedRotation()
    {
        float totalAngleSize = ZERO_SPEED_ANGLE - MAX_SPEED_ANGLE;

        float speedNormalized = speed / speedMax;

        return ZERO_SPEED_ANGLE - speedNormalized * totalAngleSize;
    }
}



結果圖:


1 則留言:

  1. 請問儀錶板的指針是怎麼出現的?
    這是unity 跳出的錯誤訊息
    感恩
    UnassignedReferenceException: The variable needleTranform of Canvas_Obj has not been assigned.
    You probably need to assign the needleTranform variable of the Canvas_Obj script in the inspector.
    UnityEngine.Transform.set_rotation (UnityEngine.Quaternion value) (at <10564ed154d647e194bef4aef8878649>:0)
    UnityEngine.Transform.set_eulerAngles (UnityEngine.Vector3 value) (at <10564ed154d647e194bef4aef8878649>:0)
    Canvas_Obj.Update () (at Assets/Canvas_Obj.cs:33)

    回覆刪除