【Unity】ゲーム画面をブラウザいっぱいに表示し、リサイズに追従させる

このサイトで公開しているゲームを、別タブで開けるようにしたかったのですが、Unityをブラウザの画面いっぱいに表示するのが少し大変だったので備忘録として残しておきます。

まず、WebGLでビルドされたデータの中にあるindex.htmlを編集していきます。

スクロールバーを表示させたくないので#unity-container に overflow: hidden; を設定します。
また、#unity-containerにはdata-aspect-w=800,data-aspect-h=400という二つの属性も追加します。
これはJavaScript側で縦横比の計算に利用するために使うので、自分のゲームのサイズを入力してください。以下のようになっていればOKです。

html
<div id="unity-container" style="overflow: hidden;" class="unity-desktop" data-aspect-w="800" data-aspect-h="400">


#unity-footerは非表示にしたかったのでdisplay: none;を設定しました。

あとは
// Desktop style: Render the game canvas in a window that can be maximized to fullscreen:
というコメントがある場所を探してください。
その下にある
canvas.style.width = "100%";
canvas.style.height = "100%";
こちらのコードが100%でなければ100%に変更してください。

ここまでの編集が完了したら以下のJSを読み込ませてください。

javascript

         function resizeCanvas() {
            const container = document.getElementById('unity-container');

            // 1. HTMLのカスタム属性から比率を読み込む
            const preferred_width = parseInt(container.dataset.aspectW, 10);
            const preferred_height = parseInt(container.dataset.aspectH, 10);
            console.log(preferred_width);
            console.log(preferred_height);
            if (isNaN(preferred_width) || isNaN(preferred_height) || preferred_width <= 0 || preferred_height <= 0) {
                 console.error('アスペクト比のデータが不正です。');
                 return;
            }

            // 比率を計算 (幅/高さ)
            const preferred_aspect_ratio = preferred_width / preferred_height;
            // 2. ウィンドウサイズを取得            
            const window_width = window.innerWidth;
            const window_height = window.innerHeight;

            let width = preferred_width;
            let height = preferred_height;
            
            // 3. Contain ロジックの実行
            
            // 現在のウィンドウの使用可能領域の縦横比 (幅/高さ)
            const window_aspect_ratio = window_width / window_height;
            if (window_aspect_ratio >= preferred_aspect_ratio) {
                // ウィンドウがゲームより横長か同じ比率の場合: 高さをウィンドウに合わせる
                // 高さを使って新しい幅を計算: new_width = preferred_aspect_ratio * new_height
                width = preferred_aspect_ratio * window_height; 
                height = window_height;
            } else {
                // ウィンドウがゲームより縦長の場合: 幅をウィンドウに合わせる
                // 幅を使って新しい高さを計算: new_height = new_width / preferred_aspect_ratio
                width = window_width;
                height = window_width / preferred_aspect_ratio;
            }
            
            // 4. サイズの適用
            container.style.width = `${Math.round(width)}px`;
            container.style.height = `${Math.round(height)}px`;

        }

        // 初期ロード時とウィンドウリサイズ時に実行
        window.addEventListener('load', resizeCanvas);
        window.addEventListener('resize', resizeCanvas);
        
        // 念のため初期実行
        resizeCanvas();
    

以上でゲームが画面幅いっぱいに表示されて、ブラウザの幅を変えても追従するようになります。
サンプルはこちら

記事一覧へ戻る