zaterdag 7 mei 2011

XNA Minitut!

In order to make a dual texture effect in XNA, but retain the functionalities of the basic effect (in case you can't write your own shaders, E.g. on the phone), I figured out a workaround.

here's a piece of code, I'll explain it afterwards

private Texture2D BaseTexture, SecondTexture, FinalRenderTex, ;
private RenderTarget2D ProcessTexTarget;

graphics.GraphicsDevice.SetRenderTarget(ProcessTexTarget);

Spritebatch.Begin();
Spritebatch.Draw(BaseTexture, new Rectangle(0, 0, 1024, 1024), new Rectangle(0, 0, 1024, 1024), Color.White);
Spritebatch.Draw(SecondTexture, new Rectangle(0, 0, 1024, 1024), Rect, Color.White);
Spritebatch.End();

graphics.GraphicsDevice.SetRenderTarget(null);
FinalRenderTex = ProcessTexTarget as Texture2D;

I've gone ahead and colourcoded it for clarity.

first we make the necessary textures and  a rendertarget, that is the Blue section of code.
BaseTexture and SecondTexture are the ones we will be mixing, FinalRenderTex will be the Texture we will write to.
ProcessTexTarget, finally, is the render target we will use to do that.
usually, the rendertarget used is the backbuffer, which is then drawn onto the screen though the XNA content pipeline.

In the Yellow line, rendertargets really get interesting. There, we change the render target drawn to.

The Red block of code, the XNA spritebatch is used to draw Images onto the screen, like a 2D game, nothing special.
The second texture however is a transparent texture, and in my case I used a custom rect that is constantly redefined in the update function, that way, I'm able tho scroll through a spritesheet and animate stuff like caustics and so forth

In the Green and final block of code, the backbuffer is restored by setting the render target back to null and the the rendertarget is written to the texture. the order of the statements is important because you can't write  rendertarget to a texture while it's still enabled as the active target.

Finally, here's a final result, the way I used it!
It's not great, and it still needs a lot of work, but i'll upadte it lators. haha :D


cheers!

 

Geen opmerkingen:

Een reactie plaatsen