UnityでRawImageを使ってARをする際の備忘録
・Canvasを使うと自動的にカメラの描画範囲にフィットする上、親子関係を作って相対位置を固定する必要がないのでPlaneにはっつけつより楽
・Kinect等と連携してDepthMappingなどをする際にはRenderingPipeLineに入らないといけない気がする
どこをいじったかいまいち覚えていないので全部載っけておく
Background.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using UnityEngine.UI; | |
public class Background : MonoBehaviour { | |
public WebCamTexture wtex; | |
// Use this for initialization | |
void Start () { | |
if (WebCamTexture.devices.Length <= 0) | |
{ | |
Debug.LogError("Cannot find a camera. "); | |
return; | |
} | |
this.wtex = new WebCamTexture(); | |
wtex.Play(); | |
//tagでUIを表示するCameraを判断 | |
Camera cam = GameObject.FindGameObjectWithTag("BattleCamera").GetComponent<Camera>(); | |
Canvas canvas = transform.parent.GetComponent<Canvas>(); | |
canvas.renderMode = RenderMode.ScreenSpaceCamera; | |
canvas.planeDistance = cam.farClipPlane-0.01f; | |
canvas.worldCamera = cam; | |
RawImage rawImage = GetComponent<RawImage>(); | |
rawImage.texture = wtex; | |
//rawImage.SetNativeSize(); | |
RectTransform recTrans = GetComponent<RectTransform>(); | |
//recTrans.anchoredPosition = new Vector2(0.5f, 0.5f); | |
float scale = ((wtex.width / wtex.height) > cam.aspect) ? ((float)cam.pixelHeight/wtex.width) : ((float)cam.pixelWidth / wtex.height); | |
recTrans.sizeDelta = new Vector2(scale * wtex.width, scale*wtex.height); | |
recTrans.Rotate(new Vector3(0, 0, -90)); | |
wtex.Stop(); | |
} | |
// Update is called once per frame | |
void Update () { | |
} | |
} |
今回の実装はAndroidようだったので、取得したWebcamTextureを90°回転させている
CanvasのRenderCameraに、Canvasを表示させたいカメラを指定するのを忘れないように
UIのRectTransformはTransformに相当する
WebCamTexture.Play()をしないとテクスチャに反映されないため, wtex.widthやwtex.heightが機能しないのでさっさとPlay()しておくこと
今回はゲーム開始時にARモードをいきなり使うわけではないので, 一通りの設定が終わった後にStop()させている.
本当はこのセットアップは画面遷移時にやるべき.
以上.
Posted on: 2016年8月24日, by : Lait-au-Cafe