<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sgt. Conker &#187; SpriteBatch</title>
	<atom:link href="http://www.sgtconker.com/tag/spritebatch/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Wed, 06 Jul 2011 13:29:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Article : Simple 2D Animated Sprite</title>
		<link>http://www.sgtconker.com/2009/11/article-simple-2d-animated-sprite/</link>
		<comments>http://www.sgtconker.com/2009/11/article-simple-2d-animated-sprite/#comments</comments>
		<pubDate>Sun, 15 Nov 2009 22:54:28 +0000</pubDate>
		<dc:creator>ElementCy</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Animated Sprite]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[SpriteBatch]]></category>
		<category><![CDATA[Spritesheet]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=181</guid>
		<description><![CDATA[This first part is a basic tutorial on how to make a simple animated sprite using a set of images. There are better ways to animate sprites, but this will get you the basics on how it is accomplished, so the code is simple, and not optimized.]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.ubergamermonkey.com/">Casey Young</a></h4>
<p>This article describes how to animate a 2D sprite sheet with XNA.</p>
<p>I have decided to break this article into seperate pages, starting with the basics, and then progressing towards making a simple animated sprite class.</p>
<p>This first part is a basic tutorial on how to make a simple animated sprite using a set of images. There are better ways to animate sprites, but this will get you the basics on how it is accomplished, so the code is simple, and not optimized.<br />
<span id="more-181"></span></p>
<p>First start off with creating a new XNA 3.1 project.</p>
<p style="text-align: center;"><a href="http://www.sgtconker.com/wp-content/uploads/2009/10/newProject.png"><img class="size-thumbnail wp-image-182 aligncenter" title="newProject" src="http://www.sgtconker.com/wp-content/uploads/2009/10/newProject.png" alt="newProject" width="337" height="240" /></a></p>
<p>With this newly created project, we want to add the images that we want to animate.<br />
<a href="http://www.sgtconker.com/wp-content/uploads/2009/10/scribbles.zip">Click here</a> for the images to use. Add those to the project's content folder.</p>
<p>Next we want to add a few private variables to the Game1.cs file.</p>
<pre class="brush: csharp; title: ;">
public class Game1 : Microsoft.Xna.Framework.Game
	{
		GraphicsDeviceManager graphics;
		SpriteBatch spriteBatch;

		private List scribbles;  // a list of the textures we are going to animate
		private Vector2 scribbleOrigin;  // the center of the sprite
		private Vector2 scribblePos; // where to draw the sprite
		private int frameCount;  // how many frames are there to animate
		private float timePerFrame; // how long to display each frame
		private float totalElapsed;  // how long has it elapsed.
		private int currentFrame;  // what frame are we on
		private int framesPerSec; // how many frames of animation do we want to show per second.
...
</pre>
<p>This will get all the variables to animate the textures to make a nice animated sprite. Next you want to load up the textures, and set the variables with their default values. You want to do that in LoadContent in Game1.cs.</p>
<pre class="brush: csharp; title: ;">
		protected override void LoadContent()
		{
			// Create a new SpriteBatch, which can be used to draw textures.
			spriteBatch = new SpriteBatch(GraphicsDevice);

			// init the list
			scribbles = new List();
			// loop thru all the textures, and add them to the list
			for (int i = 1; i &lt;= 10; i++)
			{
				if(i &lt; 10)
					scribbles.Add(Content.Load(&quot;scribble0&quot; + i));
				else
					scribbles.Add(Content.Load(&quot;scribble&quot; + i));
			}
			// set the number of frames to the size of the List
			frameCount = scribbles.Count;
			// how many frames do we want to show a sec?  15 looked like a good number
			framesPerSec = 15;
			// compute how long it we should show each frame
			timePerFrame = (float) 1/framesPerSec;
			// we want to start from the first frame
			currentFrame = 0;
			// just started, so elapse is 0
			totalElapsed = 0;
			// get the middle of the first texture (each texture is teh same size, so we can use the first one only)
			scribbleOrigin = new Vector2(scribbles[0].Width / 2, scribbles[0].Height / 2);
			// get the center of the current display
			scribblePos = new Vector2(graphics.PreferredBackBufferWidth/2, graphics.PreferredBackBufferHeight/2);
		}
</pre>
<p>With all the variables setup and the textures loaded, lets get the logic in to start animating the sprite. To do this, we want to add the following code to the Update function in Game1.cs so it looks like the following:</p>
<pre class="brush: csharp; title: ;">
		protected override void Update(GameTime gameTime)
		{
			// Allows the game to exit
			if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
				this.Exit();

			float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
			totalElapsed += elapsed;

			if (totalElapsed &gt; timePerFrame)
			{
				currentFrame++;
				// we want to keep the current frame betwee 0 and frameCount -1
				currentFrame = currentFrame % frameCount;
				// reset the total elapsed time.
				totalElapsed -= timePerFrame;
			}

			base.Update(gameTime);
		}
</pre>
<p>We are almost done here. Only thing that is left is to draw the sprite. To do this, we want to add the following code to the Draw function in Game1.cs.</p>
<pre class="brush: csharp; title: ;">
protected override void Draw(GameTime gameTime)
		{
			GraphicsDevice.Clear(Color.CornflowerBlue);

			spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred,
							  SaveStateMode.SaveState);

			spriteBatch.Draw(scribbles[currentFrame], scribblePos, null, Color.White, 0,
				scribbleOrigin, 1.0f, SpriteEffects.None, 0.6f);

			spriteBatch.End();

			base.Draw(gameTime);
		}
</pre>
<p>Once you add that, compile the project and run it. You should see a big scribble animating on the center of your screen.</p>
<p>To download the full project for this part of the article with images and source code, <a href="http://www.sgtconker.com/wp-content/uploads/2009/11/AnimateThis.zip">click here</a>.</p>
<p>Up on the next page, we will merge the images into a sprite sheet, and do the animation with just 1 texture!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/11/article-simple-2d-animated-sprite/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Article: Simply Rendertargets</title>
		<link>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/</link>
		<comments>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:21:58 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[RenderTarget]]></category>
		<category><![CDATA[Shader]]></category>
		<category><![CDATA[SpriteBatch]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=23</guid>
		<description><![CDATA[This article describes how to use RenderTargets to draw a portion of the screen or an image using SpriteBatch.]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.conkerjo.com/">Conkerjo</a></h4>
<p>This article describes how to use RenderTargets to draw a portion of the screen or an image using SpriteBatch.<br />
<span id="more-23"></span><br />
Here's an image of our game.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/background.png"><br />
<img style="display:inline;border-width:0;" title="background" src="http://conkerjo.files.wordpress.com/2009/05/background_thumb.png" border="0" alt="background" width="244" height="184" /></a></p>
<p>And here is how we want the result to look</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/pieview.jpg"><img style="display:inline;border-width:0;" title="pieview" src="http://conkerjo.files.wordpress.com/2009/05/pieview_thumb.jpg" border="0" alt="pieview" width="244" height="192" /><br />
</a></p>
<p>What you see here is the game scene drawn, with a triangle portion visible and the rest not so much. My favourite way to achieve this is to use 2 RenderTargets, A VERY simple Effect(shader) and good old SpriteBatch.<br />
So what do we use all this for?</p>
<p>First we need to draw the game scene. There is a way around this but to make things easier to understand we will draw this to a RenderTarget. Simply put, a RenderTarget is an imaginary “screen” to draw to which you can specify the size of.<br />
Then once done, you can use the texture like any normal Texture2D you might load from the Content Pipeline.</p>
<p>To draw the scene we first want to set the correct RenderTarget, then use spritebatch just like you would to draw any other sprite. Like this.</p>
<pre class="brush: csharp; title: ;">
    GraphicsDevice.SetRenderTarget(0, _gameRT);
    //Clear the RT screen
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();
    //Draw the game
    spriteBatch.Draw(
        _gameBackground,
        Vector2.Zero,
        Color.White);

    spriteBatch.End();
</pre>
<p>Simple uh?</p>
<p>Now we need to create another RenderTarget, and Draw a triangle to it. This will never be displayed in the final scene. Although with the RenderTarget it allows you to if you so desire, maybe for debugging purposes?</p>
<pre class="brush: csharp; title: ;">

            GraphicsDevice.SetRenderTarget(0, _lightRT);
            //Clears the screen transparent.
            GraphicsDevice.Clear(Color.TransparentBlack);
            spriteBatch.Begin();

            spriteBatch.Draw(
                _triangle,
                Vector2.Zero,
                Color.White);

            spriteBatch.End();
</pre>
<p>This code is almost identical to the last except we draw the _triangle Texture which looks like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/triangle.png"><img style="display:inline;border-width:0;" title="triangle" src="http://conkerjo.files.wordpress.com/2009/05/triangle_thumb.png" border="0" alt="triangle" width="244" height="124" /></a></p>
<p>And we use the color transparent black.</p>
<p>The final thing we need to do now is draw it to the scene.</p>
<p>If we just draw the triangle on top of the game scene you will see the game scene with a white triangle on top.<br />
This isnt what we want. So we use a shader to take the game scene, and change the alpha channel corresponding to the white triangle.<br />
Wherever there is a solid non transparent color pixel, this will be set to a fully non transparent pixel in the game result, however, a transparent pixel in the triangle image will result in a completely transparent pixel in the final result.<br />
Resulting in you not being able to see that pixel. The final result is like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/pieview.jpg"><br />
<img style="display:inline;border-width:0;" title="pieview" src="http://conkerjo.files.wordpress.com/2009/05/pieview_thumb.jpg" border="0" alt="pieview" width="244" height="192" /><br />
</a></p>
<p>The shader code is very simple. It is a pixel shader which takes a AlphaTexture parameter which is the texture taken from the triangle RT.<br />
It takes the alpha from that texture, and sets the coresponding pixel on the final image to be the same.</p>
<pre class="brush: csharp; title: ;">
    float4 PixelShader(float2 texCoord: TEXCOORD0) : COLOR
    {
	    float4 Color = tex2D(ScreenS, texCoord);
        float alphaLayerAlpha = tex2D(AlphaSampler, texCoord).a;
	    Color.a=alphaLayerAlpha;
        return Color;
    }
</pre>
<p>Cool?</p>
<p>To use this we just create a new Effect variable and load it in LoadContent. Call Begin/End in the appropriate places, set the parametar and hey presto. A RESULT!!!</p>
<pre class="brush: csharp; title: ;">
    _myEffect.Parameters[&amp;quot;AlphaTexture&amp;quot;].SetValue(_lightRT.GetTexture());

	spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
	_myEffect.Begin();
    _myEffect.CurrentTechnique.Passes[0].Begin();

    spriteBatch.Draw(_gameRT.GetTexture(),
        Vector2.Zero,
        Color.White);

    _myEffect.CurrentTechnique.Passes[0].End();
    _myEffect.End();
    spriteBatch.End();
</pre>
<p>To get a better grasp of the code you can download the sample project here.</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/SimplyRenderTargets.zip" target="_blank">DOWNLOAD</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article: Fading between 2 images</title>
		<link>http://www.sgtconker.com/2009/10/fading-between-2-images/</link>
		<comments>http://www.sgtconker.com/2009/10/fading-between-2-images/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 17:40:21 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[AlphaBlending]]></category>
		<category><![CDATA[SpriteBatch]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=5</guid>
		<description><![CDATA[Fading between 2 images is a very simple task using XNA, I’ve seen a lot of different ways of doing this so here’s my take on the problem.]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.conkerjo.com/">Conkerjo</a></h4>
<p><img class="alignright" style="display: inline;" title="blogimage3" src="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage3_thumb.png" alt="blogimage3" width="146" height="115" /></p>
<p>This article describes how to fade between 2 images using SpriteBatch</p>
<p>Fading between 2 images is a very simple task using XNA, I’ve seen a lot of different ways of doing this so here’s my take on the problem.</p>
<p><span id="more-5"></span></p>
<p>We need to fade from one image which is currently displaying on screen to another image we have stored in memory.</p>
<p>Here are 3 states of 2 images fading between each other.</p>
<p><strong>The Start</strong></p>
<p><a href="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage1.png"><img style="display: inline" title="blogimage1" src="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage1_thumb.png" alt="blogimage1" width="240" height="188" /></a></p>
<p><strong>The Fade</strong></p>
<p><a href="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage2.png"><img style="display: inline" title="blogimage2" src="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage2_thumb.png" alt="blogimage2" width="244" height="192" /></a></p>
<p><strong>The Result</strong></p>
<p><a href="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage3.png"><img style="display: inline" title="blogimage3" src="http://www.conkerjo.com/wp-content/uploads/2009/09/blogimage3_thumb.png" alt="blogimage3" width="244" height="192" /></a></p>
<p>To keep it simple we use functionality within the XNA framework so we don’t have to write our own. This can be done using the SpriteBatch AlphaBlend which just happens to be the default option when calling Begin on a SpriteBatch.</p>
<p>Simply call Begin, draw the image currently on screen at a reduced alpha, then draw the image you want to transition to over the top with a alpha set to the other extreme.</p>
<p>I created a class which takes care of the drawing and alpha transitioning. Once we create an instance of the CustomImage class we must call Update, passing it the elapsed time since the last frame and also call the Draw method to draw the transition.</p>
<p>If there is no transition the CustomImage will simply draw the Image set at full opacity.</p>
<p>We define the amount of time to take in a transition in the constructor of the CustomImage or it can be changed via the TransitionTime property.</p>
<p>To start a transition just pass a Texture2D to the TransitionTo method. This will begin the process of fading between the two images and will completely switch over to the new image once complete.</p>
<p>Here is the full class implementation.</p>
<pre class="brush: csharp; title: ;">
public class CustomImage
{
	private float timer;
	public CustomImage(Texture2D initialImage, Vector2 position, Vector2 origin, float transitionTime)
	{
		this.Image = initialImage;
		this.TransitionTime = transitionTime;
		this.Color = Color.White;
		this.Rotation = 0;
		this.Position = position;
		this.Origin = origin;
	}

	public float TransitionTime { get; set; }
	public Texture2D Image { get; private set; }
	public Texture2D ToImage { get; private set; }
	public Vector2 Origin { get; set; }
	public Vector2 Position { get; set; }
	public Color Color { get; set; }
	public float Rotation { get; set; }
	public void TransitionTo(Texture2D image)
	{
		if (this.ToImage != null)
		{
			return;
		}
		this.ToImage = image;
		this.timer = 0;
	}

	public void Draw(SpriteBatch batch)
	{
		if (this.ToImage == null)
		{
			batch.Draw( this.Image, this.Position, null, this.Color, this.Rotation, this.Origin, 1f, SpriteEffects.None, 0);
		}
		else
		{
			int alpha = (int)((this.timer / this.TransitionTime) * 255);
			this.DrawImage(batch, this.Image, 255 - alpha);
			this.DrawImage(batch, this.ToImage, alpha);
		}
	}

	public void Update(float elapsed)
	{
		// We must be transitioning
		if (this.ToImage != null)
		{
			this.timer += elapsed;
			if (this.timer &amp;gt;= this.TransitionTime)
			{
				this.Image = this.ToImage;
				this.ToImage = null;
			}
		}
	}

	private void DrawImage(SpriteBatch batch, Texture2D texture, int alpha)
	{
		batch.Draw( texture, this.Position, null, new Color(this.Color, (byte)alpha), this.Rotation, this.Origin, 1f, SpriteEffects.None, 0);
	}
}
</pre>
<p>To use this class we pass a Texture2D, a position, an origin and a length of time we want a transition to take.</p>
<p>Calling Draw will draw the image set until you pass a Texture2D to the TransitionTo method.</p>
<p>Here’s is the full Game code to show how I used this class in the sample which you can download at the end of the page.</p>
<pre class="brush: csharp; title: ;">
public class Game1 : Microsoft.Xna.Framework.Game
{
    private GraphicsDeviceManager graphics;
    private SpriteBatch spriteBatch;
    private SpriteFont font;
    private CustomImage image1;
    private CustomImage image2;
    private float storedTimer = 2;
    private KeyboardState currentKeyboardState, lastKeyboardState;
    private Vector2 imageSize = new Vector2(400, 300);

    public Game1()
    {
        this.graphics = new GraphicsDeviceManager(this);
        this.Content.RootDirectory = &amp;quot;Content&amp;quot;;
    }

    private Vector2 ScreenSize
    {
        get
        {
            return new Vector2(this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
        }
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadContent()
    {
        this.spriteBatch = new SpriteBatch(GraphicsDevice);
        this.font = this.Content.Load&amp;lt;spritefont&amp;gt;(&amp;quot;Fonts/Arial&amp;quot;);
        Vector2 position = new Vector2((this.ScreenSize.X / 4), this.ScreenSize.Y / 2);
        this.image1 = new CustomImage(
            this.Content.Load&amp;lt;texture2d&amp;gt;(&amp;quot;Textures/Image1&amp;quot;),
            position,
            this.imageSize / 2,
            this.storedTimer);

        position.X += this.ScreenSize.X / 2;
        this.image2 = new CustomImage(
            this.Content.Load&amp;lt;texture2d&amp;gt;(&amp;quot;Textures/Image2&amp;quot;),
            position,
            this.imageSize / 2,
            this.storedTimer);
    }

    protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        {
            this.Exit();
        }

        this.lastKeyboardState = this.currentKeyboardState;
        this.currentKeyboardState = Keyboard.GetState();

        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
        this.HandleInput();
        this.image1.Update(elapsed);
        this.image2.Update(elapsed);
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        this.GraphicsDevice.Clear(Color.Black);

        StringBuilder instructions = new StringBuilder();
        instructions.Append(&amp;quot;Space : Transition&amp;quot;);
        instructions.Append(Environment.NewLine);
        instructions.Append(&amp;quot;PgUp / PgDwn : Increase / Decrease Timer&amp;quot;);
        instructions.Append(Environment.NewLine);
        instructions.Append(string.Format(&amp;quot;Transition Time : {0}&amp;quot;, this.storedTimer));

        this.spriteBatch.Begin();

        this.spriteBatch.DrawString(this.font, instructions, new Vector2(25), Color.White);

        this.image1.Draw(this.spriteBatch);
        this.image2.Draw(this.spriteBatch);

        this.spriteBatch.End();

        base.Draw(gameTime);
    }

    private void HandleInput()
    {
        if (this.IsNewKeyPress(Keys.Space))
        {
            this.image1.TransitionTo(this.image2.Image);
            this.image2.TransitionTo(this.image1.Image);
        }
        if (this.IsNewKeyPress(Keys.PageDown))
        {
            this.storedTimer -= 0.25f;
            this.image1.TransitionTime =
                this.image2.TransitionTime = this.storedTimer;
        }
        if (this.IsNewKeyPress(Keys.PageUp))
        {
            this.storedTimer += 0.25f;
            this.image1.TransitionTime =
                this.image2.TransitionTime = this.storedTimer;
        }
    }

    private bool IsNewKeyPress(Keys keys)
    {
        return this.currentKeyboardState.IsKeyUp(keys) &amp;amp;&amp;amp; this.lastKeyboardState.IsKeyDown(keys);
    }

    private void DrawImage(Texture2D image, Vector2 position)
    {
        this.spriteBatch.Draw(image, position, null, Color.White, 0, this.imageSize / 2, 1, SpriteEffects.None, 0);
    }
}
</pre>
<p>You can download the sample project with complete working sample <a href="http://www.conkerjo.com/Downloads/Code/ImageTransition.zip" target="_blank">here</a></p>
<p>Conkerjo - www.conkerjo.com - www.twitter.com/conkerjo</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/fading-between-2-images/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

