デコシノニッキ

ホロレンジャーの戦いの記録

MRTKButtonの縦横比を楽に設定する

How to change the size of a button のページで紹介されているPressableButtonのサイズ変更がウルトラめんどくさいのでボタンのサイズを楽に設定するコンポーネントです。PressableButtonにアタッチしてください。 使うかどうかは分からない。

microsoft.github.io

f:id:haikage1755:20200608174642g:plain:w600

コードです。

using System;
using Microsoft.MixedReality.Toolkit.Input;
using UnityEngine;

namespace HoloLab.MRTK.UX.Extension
{
    public sealed class ButtonSizeHelper : MonoBehaviour
    {
        [SerializeField] private Transform backPlate = null;
        [SerializeField] private Transform frontPlate = null;
        [SerializeField] private BoxCollider buttonCollider = null;
        [SerializeField] private NearInteractionTouchable nearInteractionTouchable = null;

        [Header("Size")]
        [SerializeField] [Range(0f, 0.1f)] private float ButtonWidth;
        [SerializeField] [Range(0f, 0.1f)] private float ButtonHeight;

        private void Reset()
        {
            backPlate = transform.Find("BackPlate/Quad");
            frontPlate = transform.Find("CompressableButtonVisuals/FrontPlate");
            buttonCollider = GetComponent<BoxCollider>();
            nearInteractionTouchable = GetComponent<NearInteractionTouchable>();
            
            var scale = backPlate.transform.localScale;
            ButtonWidth = scale.x;
            ButtonHeight = scale.y;
        }

        private void OnValidate()
        {
            var parentScale = backPlate.transform.parent.localScale;
            
            backPlate.transform.localScale = new Vector3(
                ButtonWidth, ButtonHeight, backPlate.transform.localScale.z);
            
            frontPlate.transform.localScale = new Vector3(
                ButtonWidth * parentScale.x, ButtonHeight * parentScale.y, frontPlate.transform.localScale.z);

            buttonCollider.size = frontPlate.transform.localScale;
            
            var adjustedSize = new Vector2(
                Math.Abs(Vector3.Dot(buttonCollider.size, nearInteractionTouchable.LocalRight)),
                Math.Abs(Vector3.Dot(buttonCollider.size, nearInteractionTouchable.LocalUp)));
                
            nearInteractionTouchable.SetBounds(adjustedSize);
        }
    }
}

[デコシノニッキ]は、Amazon.co.jpを宣伝しリンクすることによってサイトが紹介料を獲得できる手段を提供することを目的に設定されたアフィリエイト宣伝プログラムである、Amazonアソシエイト・プログラムの参加者です。」