[SOLVED] Render texture from camera to Image

I’ve been trying to render texture from camera to Image by doing some modification to the render to texture tutorial. but it didnt work.

var RenderLayerTotexture = pc.createScript('renderLayerTotexture');

RenderLayerTotexture.attributes.add("layerName", {type: "string"});

// initialize code called once per entity
RenderLayerTotexture.prototype.initialize = function() {
    // Create a 512x512x24-bit render target with a depth buffer
    var colorBuffer = new pc.Texture(this.app.graphicsDevice, {
        width: 512,
        height: 512,
        format: pc.PIXELFORMAT_R8_G8_B8,
        autoMipmap: true
    });
    colorBuffer.minFilter = pc.FILTER_LINEAR;
    colorBuffer.magFilter = pc.FILTER_LINEAR;
    var renderTarget = new pc.RenderTarget(this.app.graphicsDevice, colorBuffer, {
        depth: true
    });

    var layer = this.app.scene.layers.getLayerByName(this.layerName);
    layer.renderTarget = renderTarget;
};
var ApplyTexture = pc.createScript('applyTexture');
ApplyTexture.attributes.add("layerName", {type: "string"});

// initialize code called once per entity
ApplyTexture.prototype.postInitialize = function() {
    var layer = this.app.scene.layers.getLayerByName(this.layerName);   
    
    // get the material on the first mesh instance this script is attached to
    // and apply the rendertarget from the layer to it's diffuse map
    var texture = this.entity.element.textureAsset;
    texture = layer.renderTarget.colorBuffer;
    console.log(texture);
};

// update code called every frame
ApplyTexture.prototype.update = function(dt) {
    
};

// swap method called for script hot-reloading
// inherit your script state here
// ApplyTexture.prototype.swap = function(old) { };

// to learn more about script anatomy, please read:
// http://developer.playcanvas.com/en/user-manual/scripting/

All I change was:

 var texture = this.entity.element.textureAsset;
    texture = layer.renderTarget.colorBuffer;
    console.log(texture);

It did say it got the texture. Where did I go wrong???

The code isn’t applying the texture to the element.

    var texture = this.entity.element.textureAsset;
    texture = layer.renderTarget.colorBuffer;
    console.log(texture);

texture is a reference to an asset and then on the next line, the reference is changed but never applied back to the element

Without testing myself, try:

this.entity.element.texture = layer.renderTarget.colorBuffer;

This tutorial also does something similar: https://developer.playcanvas.com/en/tutorials/resolution-scaling/

thanks @yaustar for the fast reply, I did just like you sugest and it works!

Hey this is a very interesting feature.
Is it possible to make the resulting texture transparent?
If yes? how?

Usually set the alpha of the clearColor of the camera to black, which is transparent.

2 Likes

thank you will try that