Unity:カメラの距離によりだんだん透明にする
目次
はじめに
カメラを近づけていくと、だんだん透明になるオブジェクトを実装しました。普段はカメラの距離でオブジェクトがいきなり非表示になるのでそのような場合に不自然にならないようにスクリプトを作ってみました。

Unityを知らない方は、ぜひ こちらの記事 をご参照ください。
Link
- Github:https://github.com/fastsystem/unity-camera-cube-hide
- デモ画面:http://www.fast-system.jp/wp-content/uploads/static/unity-camera-cube-hide/
キューブに設定したマテリアルの設定
まずは適当なキューブにマテリアルを設定します。

設定したマテリアルを選択。

マテリアルの「Rendering Mode」を「Fade」に変更します。

カメラとの距離に応じて透明にするスクリプトを追加
スクリプトを簡単に説明します。
- startDistance:透明を開始する距離
- hiddenDisanta :完全に透明になる距離
- var d = Vector3.Distance(Camera.main.transform.position, transform.position);
- カメラと現在のオブジェクトの距離を取得
- d の長さに応じてマテリアルのアルファ値(a)を変更
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FadeHidden : MonoBehaviour
{
public float startDistance = 10;
public float hiddenDisanta = 2;
void Update()
{
var d = Vector3.Distance(Camera.main.transform.position, transform.position);
var color = this.GetComponent<Renderer>().material.color;
if (d <= hiddenDisanta)
color.a = 0.0f;
else if (d <= startDistance)
color.a = (d - hiddenDisanta) / (startDistance - hiddenDisanta);
else
color.a = 1.0f;
this.GetComponent<Renderer>().material.color = color;
}
}
デモ画面
UnityでWebGL出力して、ブラウザで動作を確かめられるのでぜひ試してみてください。
よければ、SNSにシェアをお願いします!