Trouble understanding example, how is 'this.add.image' equivalent to 'this.textures.getFrame'?

Hey, I’m interested in using RenderTexture, similarly as I would in SFML. However after viewing an example, I’m left with more questions than answers.

Regarding this example (press edit): https://labs.phaser.io/view.html?src=src/game%20objects\render%20texture\render%20texture%20to%20render%20texture.js

There contains a few lines of concern:
var gridFrame = this.textures.getFrame(‘grid’);
var gridImage = this.add.image(0, 0, ‘grid’).setVisible(false).setOrigin(0);

rt1 = this.add.renderTexture(0, 0, 800, 600);
rt1.draw(gridFrame, 0, 0);
rt1.draw(gridImage, 128, 0);

I’m having trouble understanding how these two lines can display the same image.
this.textures.getFrame(‘grid’);
// Equivalent to
this.add.image(0, 0, ‘grid’).setOrigin(0);

I apologise if it is a daft question. Are one of these methods preferred and when might I want to use one over the other?

Thank you.

@turbine Not sure but I think that image object is more complex , therefore texture usage in this example should be less performance expensive.

this.textures.getFrame and this.add.image are not equivalent. this.add.image actually places the image in the scene for rendering. Essentially all the work is done in one line.

textures.getFrame simply returns a reference to the frame so that you can use it which is what happens in the lines you quote after.

The important stuff is:

var gridFrame = this.textures.getFrame('grid');
rt1 = this.add.renderTexture(0, 0, 800, 600);
rt1.draw(gridFrame, 0, 0);

That is:

  1. Reference a texture under the variable gridFrame.
  2. Add a renderTexture to the scene.
  3. Pass the gridFrame texture to the renderTexture.

You can also pass an image that has been added to the scene to the renderTexture which is what you see with:

rt1.draw(gridImage, 128, 0);

Notice when gridImage is initially added to the scene it is called with setVisible(false) which is the reason it can’t be seen until it is passed to the renderTexture.

If you were to change the code as such:

var gridFrame = this.textures.getFrame('grid');
var gridImage = this.add.image(0, 0, 'grid').setVisible(true).setOrigin(0);

//rt1 = this.add.renderTexture(0, 0, 800, 600);
//rt1.draw(gridFrame, 0, 0);
//rt1.draw(gridImage, 128, 0);
//rt1.draw(gridFrame, 256, 0);

// rt2 = this.add.renderTexture(200, 200, 800, 600);
// rt2.draw(bob, 200, 200);
// rt2.draw(rt2, 0, 0);

You would see that gridImage still renders but gridFrame does not.

Hope that makes sense.

4 Likes

Thank you everyone for clearing this up. :slight_smile:

You explained it really well B3L7.

1 Like