I asked a question earlier in the week (aquí) regarding transferring data from a rendertarget to the CPU so that collisions could be tested on it. From the responses I got there, I decided that drawing a section of the render target to a smaller render target and then retrieving that data would be a valid solution and tried to implement that.
After drawing the full sized render target (1280x1024), I switch the active render target to a smaller one (59X47 - the collision size of my players) and try to draw the section of the large render target which falls under the player onto the smaller target. At first, I thought this had worked, but then I noticed that collisions would sometimes be wildly inaccurate.
I drew the smaller render target to the screen to inspect its contents and found that it only had a handful of pixels occupied at any one time, and that these were always in the top left corner.
// Render rectangle under player from foreground to collision layer Rectangle sourceRectangle = new Rectangle(sourceX, sourceY, (int)sizeX, (int)sizeY); gd.SetRenderTarget(collisionLayer[i]); gd.Clear(Color.Transparent); spriteBatch.Draw(foregroundLayer, collisionLayer[i].Bounds, sourceRectangle, Color.White); gd.SetRenderTarget(null);
Drawing the full large render target to the smaller target results in the data carrying over successfully (though scaled, obviously), so I'm not sure what is going wrong.
// Render full target onto collision layer gd.SetRenderTarget(collisionLayer[i]); gd.Clear(Color.Transparent); spriteBatch.Draw(foregroundLayer,new Vector2(0.0f),Color.White); gd.SetRenderTarget(null);
The image below shows the large target with the small target superimposed on the top left corner. The large target's full data seems to be drawn correctly.
preguntado el 10 de marzo de 12 a las 12:03
You're not showing your
spriteBatch.End calls, but it looks like you need to move them. Specifically, you're setting your render target to null before calling spriteBatch.End, or at least it appears so from your sample code.
I set up a sample project, and when I do the following everything works as expected...
GraphicsDevice.SetRenderTarget(target); GraphicsDevice.Clear(Color.Transparent); spriteBatch.Begin(); spriteBatch.Draw(texture, target.Bounds, new Rectangle(50, 500, 100, 100), Color.White); spriteBatch.End(); GraphicsDevice.SetRenderTarget(null); GraphicsDevice.Clear(Color.CornflowerBlue); spriteBatch.Begin(); spriteBatch.Draw(texture, new Rectangle(0, 0, 640, 480), texture.Bounds, Color.White); spriteBatch.Draw(target, Vector2.Zero, target.Bounds, Color.White); spriteBatch.End();
But if I move
spriteBatch.End después de
SetRenderTarget(null) my render target is empty.