Unity3d 摄像机Camera

一、截屏效果。

  使用Camera,实现截屏效果。截屏显示在一个UI元素上。首先UI元素,必须是RawImage,不能是Image,原因在于,the Raw Image can display any texture whilst the Image can only show a Sprite texture.Raw Image可显示任何纹理,而图像只能显示精灵纹理。

  使用Camera.targetTexture属性,

 

public UnityEngine.UI.RawImage image;

Rect temp = new Rect(camera.transform.position, new Vector2(200, 200));
RenderTexture rt = new RenderTexture((int)temp.width, (int)temp.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera.targetTexture = rt;
camera.Render();

// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)temp.width, (int)temp.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(new Rect(0, 0, temp.width - 1, temp.height - 1), 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
image.texture = screenShot;

  注意点

  1. camera.Render().采用现有的Camera相关设置,手动控制执行一次渲染。
  2. RenderTexture.active = rt;所有的渲染,将数据传递到active的renderTexture,如果为空,则在主窗口中渲染所有内容。并且渲染数据自动填充renderTexture。
  3. screen.Apply();非常消耗效率。将之前的像素点变化应用,计算最终效果。所以,尽量做完其它操作,再执行Apply().如果只是拷贝数据,则可用Graphics.CopyTexture()。调用Apply可能会撤消先前调用graphics.copyTexture的结果

二、后视镜效果,即在UI摄像机下,想看到另一个摄像机看到的内容,类似与车辆的后视镜效果。

  在Project窗口内,新建一个RenderTexure资源,将renderTexture赋值给指定摄像机的targetTexture和Raw Image元素,都可用代码控制。

猜你喜欢

转载自www.cnblogs.com/shilang/p/10622757.html