渲染纹理资源(RenderTexture)

渲染纹理是一张在 GPU 上的纹理。通常我们会把它设置到相机的 目标纹理 上,使相机照射的内容通过离屏的 frambuffer 绘制到该纹理上。一般可用于制作汽车后视镜,动态阴影等功能。

使用 RenderTexture

  1. // 方法一:把 3D 相机照射的内容绘制到 UI 的精灵帧上
  2. export class CaptureToWeb extends Component {
  3. @property(SpriteComponent)
  4. sprite: SpriteComponent = null;
  5. @property(CameraComponent)
  6. camera: CameraComponent = null;
  7. protected _renderTex: RenderTexture = null;
  8. start () {
  9. const spriteframe = this.sprite.spriteFrame;
  10. const sp = new SpriteFrame();
  11. sp.reset({
  12. originalSize: spriteframe.getOriginalSize(),
  13. rect: spriteframe.getRect(),
  14. offset: spriteframe.getOffset(),
  15. isRotate: spriteframe.isRotated(),
  16. borderTop: spriteframe.insetTop,
  17. borderLeft: spriteframe.insetLeft,
  18. borderBottom: spriteframe.insetBottom,
  19. borderRight: spriteframe.insetRight,
  20. });
  21. const rendetTex = this._renderTex = new RenderTexture();
  22. rendetTex.reset({
  23. width: 256,
  24. height: 256,
  25. colorFormat: RenderTexture.PixelFormat.RGBA8888,
  26. depthStencilFormat: RenderTexture.DepthStencilFormat.DEPTH_24_STENCIL_8
  27. });
  28. this.camera.targetTexture = rendetTex;
  29. sp.texture = rendetTex;
  30. this.sprite.spriteFrame = sp;
  31. }
  32. }
  33. // 方法二:把 3D 相机照射的内容绘制到 3D 模型上
  34. export class RenderCameraToModel extends Component {
  35. @property(ModelComponent)
  36. model: ModelComponent = null;
  37. start () {
  38. // Your initialization goes here.
  39. const renderTex = new RenderTexture();
  40. renderTex.reset({
  41. width: 256,
  42. height: 256,
  43. colorFormat: RenderTexture.PixelFormat.RGBA8888,
  44. depthStencilFormat: RenderTexture.DepthStencilFormat.DEPTH_24_STENCIL_8,
  45. });
  46. const cameraComp = this.getComponent(CameraComponent);
  47. cameraComp.targetTexture = renderTex;
  48. const pass = this.model.material.passes[0];
  49. const binding = pass.getBinding('mainTexture');
  50. pass.bindTextureView(binding, renderTex.getGFXTextureView());
  51. }
  52. }

更多方法请参考:test-case-3d