<?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; 2D</title>
	<atom:link href="http://www.sgtconker.com/category/xna/2d/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>Catalin on 2D Skeletal Animations</title>
		<link>http://www.sgtconker.com/2011/06/catalin-on-2d-skeletal-animations/</link>
		<comments>http://www.sgtconker.com/2011/06/catalin-on-2d-skeletal-animations/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 19:15:16 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Animation]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Catalin Zima]]></category>
		<category><![CDATA[Skeletons]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/06/catalin-on-2d-skeletal-animations/</guid>
		<description><![CDATA[Catalin “Too Proud To Self-promote” Zima (you might know him as our local XNA MVP Captain ZSquare) has a nice write-up of 2D Skeletal Animations over at his blog. So, if you ever wondered what the benefits of skeletal animations in the 2D world as compared to our beloved sprite sheets are, his post would [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.catalinzima.com/">Catalin “Too Proud To Self-promote” Zima</a> (you might know him as our local XNA MVP Captain ZSquare) has a nice write-up of <a href="http://www.catalinzima.com/2011/06/2d-skeletal-animations/">2D Skeletal Animations over at his blog</a>. So, if you ever wondered what the benefits of skeletal animations in the 2D world as compared to our beloved sprite sheets are, <a href="http://www.catalinzima.com/2011/06/2d-skeletal-animations/">his post would be your starting point</a> to explore this very topic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/06/catalin-on-2d-skeletal-animations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dedication for Captain boki</title>
		<link>http://www.sgtconker.com/2011/01/dedication-for-captain-boki/</link>
		<comments>http://www.sgtconker.com/2011/01/dedication-for-captain-boki/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 22:13:27 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Dedication]]></category>
		<category><![CDATA[for boki]]></category>
		<category><![CDATA[screenshot]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1952</guid>
		<description><![CDATA[And here's the screenshots for Captain boki  

Best wishes,
Captain ZSquare
]]></description>
			<content:encoded><![CDATA[<p>And here's the screenshots for <a href="http://www.sgtconker.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/">Captain boki</a> <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.amusedsloth.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/"><img class="alignnone" title="With love" src="http://www.amusedsloth.com/wp-content/uploads/2011/01/Pinch3.png" alt="With love" width="173" height="288" /></a></p>
<p>Best wishes,</p>
<p>Captain ZSquare</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/dedication-for-captain-boki/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Screen-space deformations in XNA for Windows Phone 7</title>
		<link>http://www.sgtconker.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/</link>
		<comments>http://www.sgtconker.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 21:56:40 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Windows Phone 7]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/</guid>
		<description><![CDATA[Captain ZSquare shares his technique to do screen-space deformations on Windows Phone 7. Introduces Catalin:
Working on our games, we came across the need to do some screen-space deformations for all sorts of special effects like explosions, ‘drunk filter’, warp effects and other similar stuff. But since we’re targeting Windows Phone 7, we don’t have access [...]]]></description>
			<content:encoded><![CDATA[<p>Captain ZSquare shares his technique to do <a href="http://www.amusedsloth.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/">screen-space deformations on Windows Phone 7</a>. Introduces Catalin:</p>
<blockquote cite="http://www.amusedsloth.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/"><p>Working on our games, we came across the need to do some screen-space deformations for all sorts of special effects like explosions, ‘drunk filter’, warp effects and other similar stuff. But since we’re targeting Windows Phone 7, we don’t have access to any custom shaders (which is a bummer), so we had to be creative. In the end, the solution turned out to be rather simple, and the performance is good enough (if you don’t go overboard with the effects, of course).</p>
</blockquote>
<p>See <a href="http://www.amusedsloth.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/">the post for screen shoots <em>and</em> code</a>!</p>
<p><em>Lets see if Captain ZSquare <a href="http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass/">reposts</a> this one <a href="http://www.sgtconker.com/2011/01/xna-4-0-light-pre-pass-2/">with a screen shoot</a>, too <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/screen-space-deformations-in-xna-for-windows-phone-7/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XnaFlixel for XNA 4.0</title>
		<link>http://www.sgtconker.com/2011/01/xnaflixel-for-xna-4-0/</link>
		<comments>http://www.sgtconker.com/2011/01/xnaflixel-for-xna-4-0/#comments</comments>
		<pubDate>Sat, 15 Jan 2011 20:51:27 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[XNA 4.0]]></category>
		<category><![CDATA[XnaFlixel]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/01/xnaflixel-for-xna-4-0/</guid>
		<description><![CDATA[Someone be the handle of graydsl announced the immediate availability of XnaFlixel on GitHub. Sez the laddie:
XnaFlixel is a XNA 4.0 port of flixel (http://flixel.org). It's highly experimental now and I'm planning to break the whole API to make it more C#-ish. It's not tested on Xbox yet, so if you plan to use it, [...]]]></description>
			<content:encoded><![CDATA[<p>Someone be the handle of graydsl <a href="http://forums.create.msdn.com/forums/t/72608.aspx">announced the immediate availability</a> of <a href="https://github.com/graydsl/XnaFlixel">XnaFlixel on GitHub</a>. Sez the laddie:</p>
<blockquote><p>XnaFlixel is a XNA 4.0 port of flixel (http://flixel.org). It's highly experimental now and I'm planning to break the whole API to make it more C#-ish. It's not tested on Xbox yet, so if you plan to use it, don't expect to much.</p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/xnaflixel-for-xna-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Xnaml Component</title>
		<link>http://www.sgtconker.com/2011/01/xnaml-component/</link>
		<comments>http://www.sgtconker.com/2011/01/xnaml-component/#comments</comments>
		<pubDate>Fri, 14 Jan 2011 15:10:29 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Xnaml]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2011/01/xnaml-component/</guid>
		<description><![CDATA[Following Red Badger’s XPF here comes another Silverlight in XNA component to continue the promise of Bronzeglow: Xnaml Component. Valentin – its creator – asks for beta testers in the AppBuh forums, so head over to his contact form and, well, contact him.
]]></description>
			<content:encoded><![CDATA[<p>Following <a href="http://red-badger.com/">Red Badger</a>’s <a href="http://red-badger.com/Blog/?tag=/xpf">XPF</a> here comes another <em>Silverlight in XNA</em> component to continue the promise of Bronzeglow: <a href="http://msmvps.com/blogs/valentin/pages/xnaml-component.aspx">Xnaml Component</a>. Valentin – its creator – asks for beta testers in the <a href="http://forums.create.msdn.com/forums/t/72489.aspx">AppBuh forums</a>, so head over to his <a href="http://msmvps.com/blogs/valentin/contact.aspx">contact form</a> and, well, contact him.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2011/01/xnaml-component/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XNA Tile Engine Base Solution for WP7</title>
		<link>http://www.sgtconker.com/2010/10/xna-tile-engine-base-solution-for-wp7/</link>
		<comments>http://www.sgtconker.com/2010/10/xna-tile-engine-base-solution-for-wp7/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 14:39:41 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Gareth Williams]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Tile Engine]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1822</guid>
		<description><![CDATA[Gareth Williams has posted news of his Tile Engine solution for XNA which runs on Windows Phone 7.

And a handy list of all the features of the solution:

Suitable for side-on and top-down games
Good for platformers, RPGs, shooters, racers, adventures - anything that needs tiles!
Works in landscape or portrait with one line change.
Built on the Windows [...]]]></description>
			<content:encoded><![CDATA[<p>Gareth Williams has posted news of his Tile Engine solution for XNA which runs on Windows Phone 7.</p>
<p><object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/YtHxYnejTwQ?fs=1&amp;hl=en_GB"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/YtHxYnejTwQ?fs=1&amp;hl=en_GB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object></p>
<p>And a handy list of all the features of the solution:</p>
<ul>
<li>Suitable for side-on and top-down games</li>
<li>Good for platformers, RPGs, shooters, racers, adventures - anything that needs tiles!</li>
<li>Works in landscape or portrait with one line change.</li>
<li>Built on the Windows Phone 7 XNA Gamestate Management engine sample.</li>
<li>Uses Nick Gravelyn's content pipeline extension for the "Tiled" editor.</li>
<li>Simple but flexible camera class that clamps to the map boundaries.</li>
<li>Draw the whole map at once, or one layer at a time for flexibility.</li>
<li>Parallax scrolling simply by adding a couple of properties to a layer in Tiled.</li>
<li>An overload to draw a layer as "shadows" by drawing offset+black+semi-transparent.</li>
<li>Per-pixel colour-based collision detection on specified layers/tilesets.</li>
</ul>
<p>There's a link to the sample project on his blog, please read the rest of this post along with trying out the sample.<br />
<a href="http://fatsweb.blogspot.com/2010/09/phone-7-xna-tile-engine-base-solution.html?spref=tw">Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/10/xna-tile-engine-base-solution-for-wp7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jemgine: Now for XNA 4.0</title>
		<link>http://www.sgtconker.com/2010/09/jemgine-now-for-xna-4-0/</link>
		<comments>http://www.sgtconker.com/2010/09/jemgine-now-for-xna-4-0/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 19:11:27 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[2D Engine]]></category>
		<category><![CDATA[Blecki]]></category>
		<category><![CDATA[JEmgine]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1812</guid>
		<description><![CDATA[Mr "My engine is better than your engine" Blecki has very kindly updated his XNA Engine to XNA 4.0.
A reminder that you can get the latest source on codeplex
There isnt much else to but .. Awsomesauce... you should go download it immediately. 
Read direct from the source here 
]]></description>
			<content:encoded><![CDATA[<p><a href="http://jemgine.omnisu.com/">Mr "My engine is better than your engine" Blecki</a> has very kindly updated his XNA Engine to XNA 4.0.<br />
A reminder that you can get the latest source on <a href="http://jemgine.omnisu.com/?p=437">codeplex</a></p>
<p>There isnt much else to but .. Awsomesauce... you should go download it immediately. </p>
<p>Read direct from the <a href="http://jemgine.omnisu.com/?p=437">source here</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/jemgine-now-for-xna-4-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Article: Arbitrarily Shaped Secondary 2D Viewports</title>
		<link>http://www.sgtconker.com/2010/09/article-arbitrarily-shaped-secondary-2d-viewports/</link>
		<comments>http://www.sgtconker.com/2010/09/article-arbitrarily-shaped-secondary-2d-viewports/#comments</comments>
		<pubDate>Mon, 13 Sep 2010 20:42:24 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Arbitrary Shaped]]></category>
		<category><![CDATA[Harry Trautmann]]></category>
		<category><![CDATA[Inkscape]]></category>
		<category><![CDATA[Secondary Viewports]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1760</guid>
		<description><![CDATA[by Harry Trautmann

This tutorial shows a technique to implement a secondary 2D viewport which has a shape that does not need to be rectangular, but can be customized by the programmer. Even moving sprite shapes are possible. Utilized code techniques: secondary rendertarget (of XNA Game Studio 3.1) and an alphamap by a pixelshader (PS 2.0).
This [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Harry Trautmann</h4>
<p style="text-align: center;"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSecondViewport.png"><img class="aligncenter" title="Arbitrary Shaped Viewports" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSecondViewport.png" alt="" width="479" height="361" /></a></p>
<p>This tutorial shows a technique to implement a secondary 2D viewport which has a shape that does not need to be rectangular, but can be customized by the programmer. Even moving sprite shapes are possible. Utilized code techniques: secondary rendertarget (of XNA Game Studio 3.1) and an alphamap by a pixelshader (PS 2.0).</p>
<p>This tutorial is for beginner to intermediate level programmers. At least you should know the oo basics and know the nitty-gritty about the XNA framework. Also, basic shader programming is explained somewhere else (e. g. here: <a href="http://www.sgtconker.com/2009/11/crash-course-in-hlsl/">http://www.sgtconker.com/2009/11/crash-course-in-hlsl/</a>)</p>
<h2><span id="more-1760"></span>What is a Secondary Viewport?</h2>
<p>Normally games let the player watch one scene at a given time. In a jump'n'run game the player's avatar is somewhere in the middle of the screen, and the game always displays a cut-out part of the world depending on the avatar´s position. This cut-out part is the primary (main) viewport.</p>
<p>A secondary viewport would be some kind of a window inside of the main viewport that shows either the same scene by another view or a completely different scene.</p>
<h2>What could a secondary viewport be useful for?</h2>
<p>I can think of at least 5 applications:</p>
<ol>
<li>Surveillance cameras: the player can behold faraway places while the screen mainly displays some totally other scene. E. g. this could be useful in multiplayer games where one could be able to place such cameras inside of the enemy´s base for spy actions.</li>
<li>Dimension gates: through the door you see a scene of some fantasy land that gets real when you enter.</li>
<li>Microscope: works by applying some magnifying factor.</li>
<li>Mirrors: as the player´s avatar walks by, the secondary viewport shows it horizontally mirrorred and somewhat displaced.</li>
<li>Special FX: do you remember the intro of some old James Bond movie, where some scenes where shown inside of the shape of a dancer? In principle this can be done with a secondary viewport, when the alpha map is a moving sprite.</li>
</ol>
<p>These are just some suggestions for where secondary viewports are useful. Nevertheless this tutorial concentrates on showing how the shape of the viewport can be free from a rectangular nature.</p>
<h2>Principle</h2>
<p>The secondary viewport consists of a secondary <em>RenderTarget</em> object and an alphamap. The alphamap consists of a texture which defines its shape and a pixelshader that modulates pixels by the alphamap texture. The drawing process of the secondary viewport follows these steps:</p>
<ol>
<li>The spectated scene gets rendered onto the secondary rendertarget.</li>
<li>A texture of the secondary rendertarget is kept. It will be drawn later on.</li>
<li>Then the main scene is drawn onto the videocard´s own rendertarget (main rendertarget).</li>
<li> Finally the texture of the spectated scene is drawn onto the main rendertarget by applying the alphamap as a shader effect.</li>
</ol>
<h2>Create the Background Scene</h2>
<p>First we need a scene that we can spectate by the secondary viewport. Understanding the scene implementation itself is not required to comprehend the rest of the tutorial. So to avoid too much confusion we keep the scene code rather simple and encapsulate it mostly into the Star class. Since it is really easy to understand we just skim over some hotspots. Here (<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/SecondaryViewport-SceneOnly.zip">SecondaryViewport-SceneOnly.zip</a>) is the code that produces the plain scene. In case you are unsure, if some code belongs to the scene or to the viewport implementation, you can compare this project and the project we will build for the viewport to see the differences.</p>
<h3>Idea</h3>
<div class="wp-caption aligncenter" style="width: 492px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSceneOnly.png"><img class=" " title="Scene Only" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSceneOnly.png" alt="" width="482" height="361" /></a><p class="wp-caption-text">Figure 1: Only the Scene - no secondary viewport yet</p></div>
<p>A field of randomly sized, randomly moving sprite stars will do the trick. The <em>Game1</em> object will have an array of <em>Star</em> objects that will get updated and drawn. Figure 1 shows the resulting scene that yet misses the secondary viewport.</p>
<h3>The <em>Star</em> class</h3>
<p>To keep the scene code as far as possible separated from the code that actually implements the secondary viewport, we have the <em>Star</em> class. A <em>Star</em> object keeps track of its position, rotation, moving speed, moving direction and has a unique (also random) color. Each <em>Star</em> object can only move inside of a rectangular area that gets set in the constructor.</p>
<p>Only few things are notably about this class. First all objects share the same texture graphic. The first created <em>Star</em> object loads the static <em>Texture2D</em> member during its constructor call. The same thing applies to the <em>Random</em> value generator.</p>
<pre class="brush: csharp; title: ;">
protected static Texture2D _texStar = null;
protected static Random _randGen = null;
</pre>
<p>These static objects get created in the constructor call of the first Star object.</p>
<pre class="brush: csharp; title: ;">
if (_texStar == null)
        _texStar = game.Content.Load&lt;Texture2D&gt;(&quot;textures//star&quot;);
if (_randGen == null)
        _randGen = new Random();
</pre>
<p>Then in Update, the movement direction of a Star object gets reversed when the position collides with one of the initially set movement boundaries.</p>
<pre class="brush: csharp; title: ;">
if (_pos.X &lt;= _bounds.X || _pos.X &gt;= _bounds.X + _bounds.Width) {
        _move.X *= -1.0f;
        _pos.X = MathHelper.Clamp(_pos.X, _bounds.X, _bounds.X + _bounds.Width);
}// fi
if (_pos.Y &lt;= _bounds.Y || _pos.Y &gt;= _bounds.Y + _bounds.Height) {
        _move.Y *= -1.0f;
        _pos.Y = MathHelper.Clamp(_pos.Y, _bounds.Y, _bounds.Y + _bounds.Height);
}// fi
</pre>
<p>Last, also in Update, the rotation gets clipped to some value inside of the range 0 to 2 pi.</p>
<pre class="brush: csharp; title: ;">
_rot += (float) (_rotInc * gametime.ElapsedGameTime.TotalMilliseconds);
if (_rot &lt; 0.0f) {
        _rot = MathHelper.TwoPi + (_rot % MathHelper.TwoPi);
} else {
        _rot = _rot % MathHelper.TwoPi;
}// fi
</pre>
<h2>Creating the Scene</h2>
<p>The Game1 object has an array of Star objects.</p>
<pre class="brush: csharp; title: ;">
protected Star[] _stars;
</pre>
<p>It gets created inside of the LoadContent method. Each Star´s movement gets limited to the main window´s ClientBounds rectangle.</p>
<pre class="brush: csharp; title: ;">
Rectangle rcWin = new Rectangle(0, 0, Window.ClientBounds.Width,
                                             Window.ClientBounds.Height);
_stars = new Star[_StarCount];
for (int i = 0; i &lt; _StarCount; i++)
        _stars[i] = new Star(this, rcWin);
</pre>
<p>Note, that in LoadContent a font gets loaded ("Arial" should be available on any Windows system). It´s used for drawing some coordinates on the screen so the user can orientate easier.</p>
<pre class="brush: csharp; title: ;">
_font = Content.Load&lt;SpriteFont&gt;(&quot;fonts\\Arial10&quot;);
</pre>
<h2>Updating the Scene</h2>
<p>Straightforward. For each Star its Update method gets called.</p>
<pre class="brush: csharp; title: ;">
for (int i = 0; i &lt; _StarCount; i++)
        _stars[i].Update(gameTime);
</pre>
<h2>Drawing the Scene</h2>
<p>Each Star has its Draw method called and now and then we draw some coordinate values.</p>
<pre class="brush: csharp; title: ;">
GraphicsDevice.Clear(Color.White);
_spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate,
        SaveStateMode.None);
        // The stars know how to draw by themselves.
        for (int i = 0; i &lt; _StarCount; i++)
                _stars[i].Draw(_spriteBatch);
        // For easier orientation draw some coordinate values.
        float chunksW = Window.ClientBounds.Width / 5;
        float chunksH = Window.ClientBounds.Height / 5;
        for (int x=0; x &lt; 5; x++)
                for (int y = 0; y &lt; 5; y++) {
                        _spriteBatch.DrawString(_font, x.ToString() + &quot;/&quot; + y.ToString(),
                                new Vector2(chunksW * (0.5f + x), chunksH * (0.5f + y)), Color.Black);
                }// for
        _spriteBatch.End();
</pre>
<h2>Create the Alphamap Texture</h2>
<p>Now that we have a scene, let´s create the texture for the alphamap. This texture defines the actual shape of the secondary viewport. The texture gets interpreted as a grayscale image. The darker a pixel is in this image, the more transparent the pixel of an image onto which the alphamap gets applied will be. This means a pixel of the alphamap that is completely black, will modulate an incoming pixel to be completely transparent and a pixel of the alphamap that is completely white will modulate an incoming pixel to be completely opaque (i. e. retaining its original color value).<br />
Notes:</p>
<ul>
<li>The alpha value of a pixel in the alphamap texture gets ignored completely. Of course you could use the alpha value of the pixels instead of grayscale, but its easier to see the shape of the map in the image editor by using grayscale.</li>
<li> You can use any image editor to create the alphamap. Personally I favour <a href="http://www.inkscape.org/">Inkscape</a> which can be used by a GNU license. If you never worked with a vector graphics editor before you may find the following tips useful when creating the alphamap texture.</li>
</ul>
<h3>1. Show the layers</h3>
<p>Select the main menu option "Layer / Layers..." (figure 2). It displays the "Layers" window where you can see the layers of the current Inkscape image. Think of a layer being like a transparent sheet on an overhead light projector. The "plus" button creates a new layer, the "minus" button deletes the selected layer. By clicking on the "eye" symbol everything drawn on that layer gets hidden or shown. Create a new layer and rename it by clicking on its name e. g. as "background".</p>
<div class="wp-caption aligncenter" style="width: 438px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/inkscape_1_1_layers.png"><img title="Inkscape Layers" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/inkscape_1_1_layers.png" alt="" width="428" height="412" /></a><p class="wp-caption-text">Figure 2: Main menu option &quot;Layer / Layers...&quot; in Inkscape.</p></div>
<h3>2. Create a black background</h3>
<p>Select the "background" layer. Then click on the black color at the bottom of the Inkscape window to have black assigned as the color that fills any shape you will draw. On the left side of the Inkscape window you find the "Toolbox" toolbar. Click the "square" button ("Create rectangles and squares") and draw a square onto the image. The results should look similar to figure 3.</p>
<div class="wp-caption alignnone" style="width: 476px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_2_1.png"><img class=" " title="Black BAckground" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_2_1.png" alt="" width="466" height="502" /></a><p class="wp-caption-text">Figure 3: Step 2, drawing a rectangular background for the alphamap.</p></div>
<h3>3. Create a sphere</h3>
<p>Create another layer (e. g. called "alphashape"). Make sure, that layer is selected. Select the white color at the bottom of the Inkscape window. Then click the "circle" tool ("Create circles, ellipses, and arcs") in the toolbox and draw a spherical object inside of the black background rectangle. The results should look similar to figure 4.</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_3_1.png"><img class="alignnone" title="Figure 4: Step 3, rectangular background with sphere on it." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_3_1.png" alt="Figure 4: Step 3, rectangular background with sphere on it." width="464" height="502" /></a></p>
<h3>4. Apply a gradient to the sphere shape</h3>
<p>First show the "Fill and Stroke" colors by selecting the main menu option "Object / Fill and Stroke...". Above the "Layers" window another window named "Fill and Stroke" should be displayed now. Make sure the "Fill" tab and inside of the drawing area the white sphere are selected (You may need to click the 'select' tool ("Select and transform objects") in the toolbox first to select the sphere). Now click the 'gradient' tool ("Create and edit gradients") in the toolbox. Then press the left mouse button in the center of the white sphere and drag the cursor towards its edge. The results should look similar to figure 5. Since we want to have most of our alphamap opaque, we have to modify the gradient. Press the "Edit..." button ("Edit the stops of the gradient") of the 'tool controls' bar (figure 6). In the appearing "Gradient editor" window press the "Add stop" button. Behold new control points appearing on the gradient lines (figure 7). Close the gradient editor window and click on one of these new points to have it selected in the "Fill and Stroke" window. Now set the "Opacity, %" gauge to "100.0" (figure 8). Finally press the left mouse button onto the new gradient point and drag it towards the edge of the spherical object (figure 9).</p>
<div class="wp-caption alignnone" style="width: 476px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_1.png"><img class=" " title="Figure 5: Step 4a, a simple gradient applied to the sphere." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_1.png" alt="" width="466" height="501" /></a><p class="wp-caption-text">Figure 5: Step 4a, a simple gradient applied to the sphere.</p></div>
<div class="wp-caption alignnone" style="width: 593px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_2.png"><img title="Figure 6: Step 4b, the gradient edit button." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_2.png" alt="" width="583" height="83" /></a><p class="wp-caption-text">Figure 6: Step 4b, the gradient edit button.</p></div>
<div class="wp-caption alignnone" style="width: 432px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_3.png"><img title="Figure 7: Step 4c, the new points on the gradient lines." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_3.png" alt="" width="422" height="258" /></a><p class="wp-caption-text">Figure 7: Step 4c, the new points on the gradient lines.</p></div>
<div class="wp-caption alignnone" style="width: 700px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_4.png"><img title="Figure 8: Step 4d, modify new gradient step." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_4.png" alt="" width="690" height="247" /></a><p class="wp-caption-text">Figure 8: Step 4d, modify new gradient step.</p></div>
<div class="wp-caption alignnone" style="width: 396px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_5.png"><img title="Figure 9: Step 4e, repositioning gradient step points." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_5.png" alt="" width="386" height="252" /></a><p class="wp-caption-text">Figure 9: Step 4e, repositioning gradient step points.</p></div>
<h3>5. Export the image as PNG</h3>
<p>Select the black background rectangle we created in the second step. Select the main menu entry "File / Document Properties...". Inside of the appearing "Document Properties" window in the "Custom size" box press the little plus button and then the "Resize page to drawing or selection" (figure 10). Close the "Document Properties" window. Select the main menu option "File / Export Bitmap...". Press the "Page" button to have the size of the exported bitmap fixed to the page size. Press the "Browse..." button and enter a filename and storage location for the bitmap file. Also do not forget to select PNG as file format and have the filename have a ".png" suffix. Press "Save" to close the file selection dialog. Finally press the "Export" button to actually have the image exported.</p>
<div class="wp-caption alignnone" style="width: 588px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_6.png"><img class=" " title="Figure 10: the button to have the page resized is a little bit hidden." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/Inkscape_4_6.png" alt="" width="578" height="389" /></a><p class="wp-caption-text">Figure 10: the button to have the page resized is a little bit hidden.</p></div>
<h3>6. Import the texture into the Visual C# Project</h3>
<p>Back in the MS VC# IDE do not forget to add the alphamap image to the "Content" in the project explorer.</p>
<h2>Implement the Viewport</h2>
<p>Note that in this sample the main scene and the spectated scene are the same. Therefore it is not necessary to render the scene twice. Instead the main scene gets rendered once onto the texture of the secondary rendertarget, and then this texture gets rendered twice. Otherwise, if there would be many complex objects in the scene (though obviously not the case in this tutorial), the need to render the scene itself twice could become a serious performance hit.</p>
<p>The idea in this sample is to draw a magnified cut-out of the main scene as the secondary viewport. With the mouse you can steer the cut-out rectangle.</p>
<h3>New Members of Game1</h3>
<p>The Game1 class gets some new members that are necessary for the secondary viewport.<br />
The actual secondary rendertarget. Note that this is a memory space inside of the graphics card memory.</p>
<pre class="brush: csharp; title: ;">
protected RenderTarget2D _rendtarg2;
</pre>
<p>This Texture2D object that will hold the alphamap texture that we created in the last step:</p>
<pre class="brush: csharp; title: ;">
protected Texture2D _texAlphamap;
</pre>
<p>The member that will hold the compiled pixel shader effect:</p>
<pre class="brush: csharp; title: ;">
protected Effect _fxAlphamap;
</pre>
<p>A Rectangle member will hold the rectangular cut-out of the main scene that defines the source of the secondary viewport:</p>
<pre class="brush: csharp; title: ;">
protected Rectangle _rcSrc;
</pre>
<h3>Changes to the Game1 class</h3>
<p>In <em><strong>Initialize</strong> </em>the cursor gets shown to make tracing the cut-out source easier for the user.</p>
<pre class="brush: csharp; title: ;">
IsMouseVisible = true;
</pre>
<p>In <strong><em>LoadContent</em></strong> we need to load the alphamap texture and shader effect.</p>
<pre class="brush: csharp; title: ;">
_texAlphamap = Content.Load&lt;Texture2D&gt;(&quot;textures\\alphamap&quot;);
_fxAlphamap = Content.Load&lt;Effect&gt;(&quot;shaders\\AlphaMapping&quot;);
</pre>
<p>Also in <em>LoadContent </em>the secondary rendertarget is created here by calling CreateRenderTarget:</p>
<pre class="brush: csharp; title: ;">
CreateRenderTarget();
[/csharp

Note that the secondary rendertarget always needs to be of the current size of the &lt;em&gt;GraphicsDevice&lt;/em&gt;´s backbuffer. Therefore, if you implement some screen resolution / fullscreen mode switches you will also have to call &lt;em&gt;CreateRenderTarget &lt;/em&gt;again to fit the secondary rendertarget to the new size of the backbuffer.

In &lt;strong&gt;&lt;em&gt;Update &lt;/em&gt;&lt;/strong&gt;the positional change of the mouse cursor defines the source position of the secondary viewport. The &lt;em&gt;MathHelper.Clamp&lt;/em&gt; calls make sure that the source rectangle does cover space outside of the main window.
[csharp]
        // Keep track of where the mouse is and update the viewport source.
        MouseState mouse = Mouse.GetState();
        float factor = 0.33f;
        int w = (int)Math.Round(Window.ClientBounds.Width * factor);
        int h = (int)Math.Round(Window.ClientBounds.Height * factor);
        int w2 = (int)Math.Round(Window.ClientBounds.Width * factor * 0.5f);
        int h2 = (int)Math.Round(Window.ClientBounds.Height * factor * 0.5f);
        _rcSrc = new Rectangle(mouse.X - w2, mouse.Y - h2, w, h);
        _rcSrc.X = (int)MathHelper.Clamp(_rcSrc.X, 0, Window.ClientBounds.Width – w);
        _rcSrc.Y = (int)MathHelper.Clamp(_rcSrc.Y, 0, Window.ClientBounds.Height - h);
</pre>
<p>The most and most important changes to <em>Game1 </em>appear in <em><strong>Draw</strong></em>.</p>
<p>As stated above, the main scene only gets rendered once – and not onto the main rendertarget, but onto the secondary rendertarget (<em>_rendtarg2</em>). So before drawing our scene we need to set the secondary rendertarget as the current one. In order to be able to reset the main rendertarget to be the current one, we have to keep a reference in the local variable <em>rtTemp</em>.</p>
<pre class="brush: csharp; title: ;">
RenderTarget2D rtTemp = null;
rtTemp = (RenderTarget2D)_graphics.GraphicsDevice.GetRenderTarget(0);
_graphics.GraphicsDevice.SetRenderTarget(0, _rendtarg2);
</pre>
<p>After regularly drawing the scene, we keep a <em>Texture2D </em>of what we just drew. But since <em>GetTexture </em>is only possible on a <em>RenderTarget2D </em>that is not the current one, we first have to reset to the original rendertarget.</p>
<pre class="brush: csharp; title: ;">
_graphics.GraphicsDevice.SetRenderTarget(0, rtTemp);
texTemp = _rendtarg2.GetTexture();
</pre>
<p>Now we´re ready to assemble the graphical output as it is to be seen by the user. So we clear the (original) rendertarget to black (just to be safe) and paint the <em>Texture2D </em>that we just rendered on it. Note that the texture gets tinted into some light blue so that it´s easier to distinguish it from the secondary viewport graphics.</p>
<pre class="brush: csharp; title: ;">
GraphicsDevice.Clear(Color.Black);
_spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate,
                              SaveStateMode.None);
_spriteBatch.Draw(texTemp,
                         Vector2.Zero, null,
                         new Color(225, 245, 255, 255),
                         0.0f, Vector2.Zero,
                         Vector2.One,
                         SpriteEffects.None, 0.0f);
_spriteBatch.End();
</pre>
<p>Finally the secondary viewport will be rendered atop of the main scene. Note that the drawing code is outsourced into a method of its own: <em>Draw2ndViewport</em>. Why? Admitted, in this sample it does not make much sense. But assuming you write a program build atop of this sample, which needs to have more than one secondary viewport (e. g. an ingame monitor wall with say 4 monitors showing what goes on elsewhere), it is easier to have a method dedicated to draw a single secondary viewport.<br />
So what does Draw2ndViewport need as input?</p>
<ol>
<li> rcOut defines the output rectangle of the secondary viewport, i. e. Its size and where it gets drawn at. We calculate this Rectangle just before the call of Draw2ndView.</li>
<li> rcSrc defines the rectangular cut-out source of the secondary viewport. Remember that we calculated this Rectangle in Update.</li>
<li> rcScreen is a Rectangle holding the size of the screen onto which the secondary viewport is to be drawn. It gets used for calculating mapping factors from incoming image space to output space. Here it is set to the main window´s extends. We calculate this Rectangle just before the call of Draw2ndView.</li>
<li> tex is the reference to the texture to be drawn. If drawing cut-out´s of a scene, then a single texture reference can be reused for this parameter.</li>
</ol>
<p>So the Draw2ndView call looks like this:</p>
<pre class="brush: csharp; title: ;">
Rectangle outrect = new Rectangle(
                     (int)Math.Round(Window.ClientBounds.Width * 0.25f),
                     0,
                     (int)Math.Round(Window.ClientBounds.Width * 0.5f),
                     (int)Math.Round(Window.ClientBounds.Height * 0.5f));
Rectangle screenrect = new Rectangle(0, 0,
                     Window.ClientBounds.Width, Window.ClientBounds.Height);
Draw2ndViewport(outrect, _rcSrc, screenrect, texTemp);
</pre>
<p>For now treat <em>Draw2ndViewport </em>as a black box. After explaining the pixelshader its workings are easier to understand, and we come back to it.</p>
<h3>How the Pixelshader works</h3>
<p>The alphamap pixelshader ("AlphaMapping.fx") has three parameter members that need to be set outside, before the effect can be applied.</p>
<ol>
<li><em>float4 srcRect</em>: these 4 <em>float</em> values defines the source area inside of the incoming image. The values can be between <em>0.0f</em> and <em>1.0f</em> as usual for texel coordinates.</li>
<li><em>float4 destRect</em>: these 4 float values define the destination area inside of the shaded image. These values too are to be inside of <em>0.0f</em> and <em>1.0f</em>.</li>
<li><em>texture AlphaMap</em>: is to hold the reference to the alphamap texture.</li>
</ol>
<p>The shader has two samplers, the first for the incoming image and the other for the alphamap.</p>
<pre class="brush: csharp; title: ;">
sampler IncomingSampler;
sampler AlphaMapSampler = sampler_state {
        Texture = &lt;AlphaMap&gt;;
        MinFilter = Linear;
        MagFilter = Linear;
        MipFilter = Linear;
        AddressU  = Mirror;
        AddressV  = Mirror;
};
</pre>
<p>The actual work of modulating pixels of the incoming image by corresponding pixels of the alphamap texture happens inside of the <em>PS_AlphaMap</em> function.</p>
<pre class="brush: csharp; title: ;">
float4 PS_AlphaMap(float2 texCoord: TEXCOORD0) : COLOR
</pre>
<p>The function receives texture coordinate inside of the texture image to be processed. Again these two float values are between<em> 0.0f</em> and <em>1.0f</em>. It returns four <em>float </em>values defining the color that the pixel at that coordinate position is to have.<br />
First we get whatever color is at the original position of the incoming texture image. <em>colOut </em>will hold the color value that <em>PS_AlphaMap</em> returns.</p>
<pre class="brush: csharp; title: ;">
float4 colOut = tex2D(IncomingSampler, texCoord);
</pre>
<p>Then we check, if the incoming coordinate is inside of the output area to be modulated by the alphamap.</p>
<pre class="brush: csharp; title: ;">
if ((texCoord[0] &gt;= destRect[0]) &amp;&amp; (texCoord[0] &lt; (destRect[0] + destRect[2])) &amp;&amp;
      (texCoord[1] &gt;= destRect[1]) &amp;&amp; (texCoord[1] &lt; (destRect[1] + destRect[3]))){
</pre>
<p>If it is not inside of the destination area, the read color is assured to stay like it is. Therefore the a value is set to opaque.</p>
<pre class="brush: csharp; title: ;">
} else {
      colOut.a = 0.0f;
}// fi
</pre>
<p>But if the coordinate is inside of the destination area, its color value gets modulated by the alphamap before returning it. Then it is necessary to respect that the source of the output color could be some other pixel than the one we currently have the coordinates for in <em>texCoord</em>. Depending on the size of the incoming texture image and the size of the destination rectangle the new source coordinate gets calculated and stored in <em>newSrc</em>. Remember that all these values are relative share values between <em>0.0f</em> and <em>1.0f</em>. Afterwards <em>colOut </em>is filled with the color of the pixel at this new coordinates in the incoming texture image.</p>
<pre class="brush: csharp; title: ;">
float2 newSrc;
float shareX = (texCoord[0] - destRect[0]) / destRect[2];
float shareY = (texCoord[1] - destRect[1]) / destRect[3];
newSrc[0] = srcRect[0] + shareX * srcRect[2];
newSrc[1] = srcRect[1] + shareY * srcRect[3];
colOut = tex2D(IncomingSampler, newSrc);
</pre>
<p>Now we have to read the color value of the alphamap that corresponds to the incoming coordinates relative to the destination rectangle size.</p>
<pre class="brush: csharp; title: ;">
float2 mappedTC;
float4 colAlphaMap;
mappedTC[0] = ((texCoord[0] - destRect[0]) / destRect[2]);
mappedTC[1] = ((texCoord[1] - destRect[1]) / destRect[3]);
colAlphaMap = tex2D(AlphaMapSampler, mappedTC);
</pre>
<p>Finally the current incoming color value gets modulated by the alphamap color value. This is done by simply multiplying the a parts of the colors and leaving the r, g, b of the incoming value as they are. Note that since the alphamap texture should be grayscale the r, g, b values should be the same for a single pixel in the alphamap texture. Therefore in the pixelshader only the r value of a pixel´s color is processed, r and b get ignored.</p>
<pre class="brush: csharp; title: ;">
colOut.a = colOut.a * colAlphaMap.r;
</pre>
<p>Finally in the technique <em>AlphaMapShader </em>the <em>Pass0 </em>defines that the <em>AlphaMapSampler </em>and the <em>PS_AlphaMap</em> functions are to be used.</p>
<pre class="brush: csharp; title: ;">
technique AlphaMapShader {
        pass Pass0 {
                AlphaBlendEnable = True;
                SrcBlend = SrcAlpha;
                DestBlend = InvSrcAlpha;
                Sampler[0] = (AlphaMapSampler);
                PixelShader = compile ps_2_0 PS_AlphaMap();
        }// Pass0
} // AlphaMapShader
</pre>
<h3>Draw 2nd Viewport</h3>
<p>So back in <em>Game1 </em>we only need to explain what <em>Draw2ndView </em>does. Actually it only sets  the parameters of the pixelshader and draws the given texture image by applying the alphamap shader – all wrapped in the <em>SpriteBatch</em>´s <em>Begin </em>and <em>End </em>methods.<br />
Setting the AlphaMap shader parameter:</p>
<pre class="brush: csharp; title: ;">
_fxAlphamap.Parameters[&quot;AlphaMap&quot;].SetValue(_texAlphamap);
</pre>
<p>For setting the srcRect shader parameter we first need to have the source rectangle mapped to share values between 0.0f and 1.0f relative to the texture´s size.</p>
<pre class="brush: csharp; title: ;">
float[] srcRect = new float[4] {
        (float) rcSrc.X / (float)tex.Width,
        (float) rcSrc.Y / (float)tex.Height,
        (float) rcSrc.Width / (float)tex.Width,
        (float) rcSrc.Height / (float)tex.Height
};
_fxAlphamap.Parameters[&quot;srcRect&quot;].SetValue(srcRect);
</pre>
<p>Setting the <em>destRect </em>shader parameter also needs mapping the values to share values, but this time relative to the output screen´s size.</p>
<pre class="brush: csharp; title: ;">
float[] destRect = new float[4];
destRect[0] = (rcOut.X + rcScreen.X) / (float)rcScreen.Width;
destRect[1] = (rcOut.Y + rcScreen.Y) / (float)rcScreen.Height;
destRect[2] = (rcOut.Width) / (float)rcScreen.Width;
destRect[3] = (rcOut.Height) / (float)rcScreen.Height;
_fxAlphamap.Parameters[&quot;destRect&quot;].SetValue(destRect);
</pre>
<p>After setting these parameters drawing the given texture by applying the shader is straightforward just like with other shaders.</p>
<pre class="brush: csharp; title: ;">
_fxAlphamap.CurrentTechnique = _fxAlphamap.Techniques[&quot;AlphaMapShader&quot;];
_fxAlphamap.Begin();
_fxAlphamap.CurrentTechnique.Passes[0].Begin();
        _spriteBatch.Draw(tex,
                        new Vector2(),
                        null,
                        Color.White,
                        0.0f, Vector2.Zero,
                        Vector2.One,
                        SpriteEffects.None, 0.0f);
_fxAlphamap.CurrentTechnique.Passes[0].End();
_fxAlphamap.End();
</pre>
<p>Figure 11 shows what the result looks like.</p>
<div class="wp-caption alignnone" style="width: 489px"><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSecondViewport.png"><img class=" " title="Figure 11: the scene with a magnifying secondary viewport." src="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/ScreenSecondViewport.png" alt="" width="479" height="361" /></a><p class="wp-caption-text">Figure 11: the scene with a magnifying secondary viewport.</p></div>
<p>Find the sample code here: <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/SecondaryViewport.zip">SecondaryViewport.zip</a>.</p>
<h2>Ideas for Extensions</h2>
<p>Homework for you!</p>
<ul>
<li>The mousewheel could steer the zoom. The zoom is controlled by the size of the rectangle defining the cut-out of the main scene.</li>
<li>Of course the spherical form of the alphamap is only a suggestion. It´s easy to reproduce, therefore it seemed appropriate for this tutorial. Actually having a completely customized alphamap shape is what this tutorial is about – go ahead and change it to whatever form you like!</li>
<li>As mentioned in the intro, the alphamap could also be a moving 2D sprite. I extended the sample of this tutorial to reflect, how this could be established. You can get the code here: <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/harry/SecondaryViewport-MovingSprite.zip">SecondaryViewport-MovingSprite.zip</a>.</li>
</ul>
<h2>License</h2>
<p>This text and any referred code is licensed under a "Creative Commons Attribution 3.0 Unported" license, which can be read here: <a href="http://creativecommons.org/licenses/by/3.0/">http://creativecommons.org/licenses/by/3.0/</a></p>
<p>The author of all text, any code and any assets found in this tutorial likes to be referred by Harry Trautmann, <a href="http://codemachinery.net">http://codemachinery.net</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-arbitrarily-shaped-secondary-2d-viewports/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Article: XNA Farseer Platform Physics Tutorial</title>
		<link>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 19:48:45 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Physics]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Farseer]]></category>
		<category><![CDATA[Platformer]]></category>
		<category><![CDATA[Roy Triesscheijn]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1756</guid>
		<description><![CDATA[by Roy Triesscheijn
Today I’m going to introduce you to a neat 2D physics engine for XNA called Farseer. With the help of this 2D physics engine we are going to create a small platform ‘game’ while introducing the important concepts of Farseer like bodies, geometry, joints and springs.
By the end of the tutorial, you'll be [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <span><a href="http://www.roy-t.nl">Roy Triesscheijn</a></span></h4>
<p>Today I’m going to introduce you to a neat 2D physics engine for XNA called Farseer. With the help of this 2D physics engine we are going to create a small platform ‘game’ while introducing the important concepts of Farseer like bodies, geometry, joints and springs.</p>
<p>By the end of the tutorial, you'll be able to build something like:</p>
<p><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="480" height="385" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/iC_Y9Tq5JeU?fs=1&amp;hl=en_US" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="480" height="385" src="http://www.youtube.com/v/iC_Y9Tq5JeU?fs=1&amp;hl=en_US" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p><span id="more-1756"></span></p>
<h2>Set-up<img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/SolutionExplorer.PNG" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/see-saw.png" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/boxboy.jpg" alt="" /><img src="file:///D:/Personal/Desktop/sgt%20conker%20contest/2010%20Tutorial%20contest%20entry/Pictures/BoxAndGround.png" alt="" /></h2>
<p>Before we can get started please download the latest stable release at <a href="http://farseerphysics.codeplex.com/">http://farseerphysics.codeplex.com</a> (at the time of writing that was 2.1.3) and extract the solution somewhere. Now also download the “Added motor to RevoluteJoint and FixedRevoluteJoint” patch at <a href="http://farseerphysics.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=70619">http://farseerphysics.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=70619</a>. You will find two files in the archive (RevoluteJoint.cs and FixedRevoluteJoint.cs) extract these and copy these over the files in “Farseer Physics 2.1.3 XNA\Dynamics\Joints”.</p>
<h2>Creating a project</h2>
<p>Now let’s fire up Visual Studio and create a new XNA 3.1 Windows Game project, call it anything you like. I’ve called it “FarseerPlatformer”. Now add the Farseer project to our solution: right click the our solution in the solution explorer and select “Add existing project”, then browse to where you’ve extracted Farseer and select the FarseerPhysicsXNA.csproj.</p>
<p style="text-align: center;"><img class="aligncenter" title="Solution Explorer" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/SolutionExplorer.PNG" alt="" width="261" height="326" /></p>
<p>Now add a reference to the FarseerPhysicsXNA project in your own project by right clicking the References folder in the solution explorer and choosing “Add reference”. Then select FarseerPhysicsXNA from the tab “Projects” and press ok.</p>
<p>If your solution explorer now looks like the picture on the left we’re ready to try and compile. Hit F6 on your keyboard. There should be no errors.</p>
<h2>My  first physics</h2>
<p>The physics simulator class is the heart of the Farseer physics engine and will control all our physics objects. Let’s create one!</p>
<p>Open Game1.cs and add the following using statements at the top of the file.</p>
<pre class="brush: csharp; title: ;">
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Dynamics;
using FarseerGames.FarseerPhysics.Factories;
using FarseerGames.FarseerPhysics.Collisions;
</pre>
<p>Now let’s create a PhysicsSimulator called physics. Add this definition at the top of the class.</p>
<pre class="brush: csharp; title: ;">
PhysicsSimulator physics;
</pre>
<p>And instantiate it by adding the following line to the end of the constructor.</p>
<pre class="brush: csharp; title: ;">
physics = new PhysicsSimulator(Vector2.UnitY * 500);
</pre>
<p>This will create a new physics simulator with a predefined gravity of (0, 500) which means that there is a constant force of strength 500 pushing everything down. 500 here is just an arbitrary number, play around with this value as much as possible to tweak the feel of your games.</p>
<p>All we need todo to make the physics simulator work is making it update every frame by adding the following line at the end of the Update method.</p>
<pre class="brush: csharp; title: ;">
physics.Update((float)gameTime.ElapsedGameTime.TotalSeconds);
</pre>
<p>So that’s it. We’re done! But well, you can’t actually see anything yet. Let’s make a very simple class called PhysicsObject. I will not put down the entire class right here, see the source code for that. However there is one method that deserves special attention:</p>
<pre class="brush: csharp; title: ;">
protected virtual void SetupPhysics(PhysicsSimulator physics,
            Vector2 position, float width, float height, float mass)
        {
            body = BodyFactory.Instance.CreateRectangleBody(physics,
                                                width, height, mass);
            body.Position = position;

            geom = GeomFactory.Instance.CreateRectangleGeom(physics,
                                                body, width, height);
            geom.FrictionCoefficient = 0.5f;
        }
</pre>
<p>In this method we create the ‘physical representation’ for our new object.  For this we need two fields: body of type Body and geom of type Geom. Body represents a handle which we can push and pull and apply all sorts of forces to. Geom (short for geometry) handles the actual collisions and friction. Both objects fire numerous events which you can handle, the most useful one is geom’s OnCollision event that we will use in the final chapter.</p>
<p>Instantiating them is very easy. Just use the apropiate factory class to get a new instances, make sure to always choose the overload that also asks for a PhysicsSimulator object so that your object is automatically registered in the simulation. Also note that the PhysicsSimulator uses the center of an object as its position, while the SpriteBatch uses the top left corner normally, take this into account when drawing by setting the origin to the center of the texture when using the SpriteBatch.<br />
Add a texture to your content project and quickly instantiate a new PhysicsObject like this:</p>
<pre class="brush: csharp; title: ;">
squareTex = Content.Load&lt;Texture2D&gt;(&quot;square&quot;);
box = new PhysicsObject(physics, new Vector2(100, 0), 64, 64, 10, squareTex);
</pre>
<p>Then add the following lines to the draw method in Game1.</p>
<pre class="brush: csharp; title: ;">
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate,
                                              SaveStateMode.SaveState);
box.Draw(spriteBatch);
spriteBatch.End();
</pre>
<p>If you run the simulation now you should see a falling square. Nifty isn’t it?</p>
<h2>Laying grounds</h2>
<p>Now we need to make some ground that will stop our square from falling down at terminal velocity. To do this we’re going to make a static body. This means that the body is unaffected by all forces but still is in our simulation, handy for making immovable objects like ground and walls. To do this neatly we will make a new class that inherits from the PhysicsObject class. Call this class StaticPhysicsObject.<br />
Because of inheritance all we have to write in this new clas is this:</p>
<pre class="brush: csharp; title: ;">
    public class StaticPhysicsObject : PhysicsObject
    {
        public StaticPhysicsObject(PhysicsSimulator physics, Vector2 position, float width, float height, Texture2D texture)
            : base(physics, position, width, height, 1, texture)
        {
            body.IsStatic = true;
        }
    }
</pre>
<p>Note how we always pass a mass of 1, mass isn’t important for a static object.</p>
<p>Create a new field StaticPhysicsObject ground in Game1 and instantiate it in LoadContent like this:</p>
<pre class="brush: csharp; title: ;">
ground = new StaticPhysicsObject(physics, new Vector2(GraphicsDevice.Viewport.Width / 2, 500), GraphicsDevice.Viewport.Width, 64, squareTex);
</pre>
<p>Don’t forget to draw it in the Draw method.</p>
<p>You should now see a square falling down  and stopping when it hits our new ground.</p>
<p><img class="alignnone" title="Box and Ground" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/BoxAndGround.png" alt="" width="100%" /></p>
<h2>Joints</h2>
<p>Let’s make the simulation a bit more interesting by creating a see-saw. Quickly add two more PhysicsObjects, instantiate them like this:</p>
<pre class="brush: csharp; title: ;">
            seeSawBottom = new PhysicsObject(physics, new Vector2(175, 300), 50, 50, 1000, squareTex);
            seeSawTop = new PhysicsObject(physics, new Vector2(175, 200), 300, 30, 25, squareTex);
</pre>
<p>And write some draw code. Now let’s fire up the simulation again. You will now see our original block smash hard into our see-saw, rolling out of screen while the see-saw almost falls apart.</p>
<p>This looks awesome, however we would like the see-saw to behave as one object, so let’s introduce a joint. A joint is a way of fixing two bodies or a body and the background together (like an axel that connects a wheel to a car). There are multiple types of joints. For an explantion of the different types of joints see this page: <a href="http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068491">http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068491</a></p>
<p>We are going to create a revolute joint, that fixes two bodies together but still alows them to rotate independently, very handy for a see-saw or a wheel. To demonstate this we will create a new class called CompositePhysicsObject as below:</p>
<pre class="brush: csharp; title: ;">
public class CompositePhysicsObject
    {
        public CompositePhysicsObject(PhysicsSimulator physics, PhysicsObject poA, PhysicsObject poB, Vector2 relativeJointPosition)
        {
            this.poA = poA;
            this.poB = poB;

            joint = JointFactory.Instance.CreateRevoluteJoint(physics, poA.body, poB.body, poA.Position + relativeJointPosition);
            poA.geom.IgnoreCollisionWith(poB.geom);
            poB.geom.IgnoreCollisionWith(poA.geom);
        }

        public virtual void Draw(SpriteBatch spriteBatch)
        {
            poA.Draw(spriteBatch);
            poB.Draw(spriteBatch);
        }

        protected RevoluteJoint joint;
        protected PhysicsObject poA;
        protected PhysicsObject poB;
    }
</pre>
<p>Just as with the bodies and geoms we create a joint with a factory. Creating a revolute joint is very easy, the second body is attached to the first body at the absolute (world) position. To make it easier to create a composite physics object we are using a relative position (or offset) from the first body. Note that you will have to make sure yourself that the bodies overlap, the second body will not be moved by creating a joint. (Note: bodies don’t have to overlap to be fixed together by joints, but this will look pretty funny).</p>
<p>We also need to make sure that the geometries of both physics objects do not register colliding with each other; else we would get some very buggy results.</p>
<p>Let’s go back to the Game1 class, add a field called seeSaw of type CompositePhysicsObject and change the load content method to look like this:</p>
<pre class="brush: csharp; title: ;">
protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            squareTex = Content.Load&lt;Texture2D&gt;(&quot;square&quot;);
            box = new PhysicsObject(physics, new Vector2(100, 0), 64, 64, 10, squareTex);
            seeSawBottom = new PhysicsObject(physics, new Vector2(175, 300), 50, 50, 1000, squareTex);
            seeSawTop = new PhysicsObject(physics, new Vector2(175, 285), 300, 30, 25, squareTex);
            seeSaw = new CompositePhysicsObject(physics, seeSawTop, seeSawBottom, new Vector2(0, 15));
            ground = new StaticPhysicsObject(physics, new Vector2(GraphicsDevice.Viewport.Width / 2, 500), GraphicsDevice.Viewport.Width, 64, squareTex);
        }
</pre>
<p>Also update the drawing method:</p>
<pre class="brush: csharp; title: ;">
protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
            box.Draw(spriteBatch);
            seeSaw.Draw(spriteBatch);
            ground.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }
</pre>
<p>Run, you will now have a box dropping on a fully functional see-saw.</p>
<h2>Springs</h2>
<p>You know what would be even cooler? If our see-saw would have a spring that would make our see-saw come back up again after our falling box hits it. With Farseer you can make numerous types of springs, for a full overview see the Springs section in the manual here: <a href="http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068498">http://www.farseergames.com/storage/farseerphysics/Manual2.1.htm#_Toc213068498</a></p>
<p>To improve our see-saw we are going to use an AngleSpring. This type of spring tries to keep two objects (or one object and the background) at a specified angle by applying a specified amount of torque (or less).</p>
<p>Let’s create a new class that inherits from our CompositePhysicsObject class. I couldn’t think of a decent name for it, so I just called it SpringPhysicsObject. This new class will compose two physics objects together (just as before) but will now also add an angle spring to try and keep two objects at a specified angle. (If you want to force two objects to always stay at a specified angle of each other you should use an angle joint, and if you want one object to always stay at a specified angle, use a fixed angle joint).</p>
<pre class="brush: csharp; title: ;">
public class SpringPhysicsObject : CompositePhysicsObject
    {
        public SpringPhysicsObject(PhysicsSimulator physics, PhysicsObject poA, PhysicsObject poB, Vector2 relativeJointPosition, float springForce, float springDampening)
            : base(physics, poA, poB, relativeJointPosition)
        {
            angleSpring = SpringFactory.Instance.CreateAngleSpring(physics, poA.body, poB.body, springForce, springDampening);
            angleSpring.MaxTorque = springForce;
        }

        protected AngleSpring angleSpring;
    }
</pre>
<p>As you can see we again don’t need to write a lot of code since inheriting from CompositePhysicsObject will already join our two bodies together. All we need to do is to create a new angle spring, as always via a factory. I think spring force and spring dampening speak for themselves. MaxTorque is the maximum amount of torque that will be applied to stay at the given angle. Note that you usually need very high values for spring force to make this work properly (just as in real life).<br />
Now that we have this new SpringPhysicsObject, replace our CompositePhysicsObject and instantiate it like this in the LoadContent method.</p>
<pre class="brush: csharp; title: ;">
seeSaw2 = new SpringPhysicsObject(physics, seeSawTop, seeSawBottom, new Vector2(0, 15), 10000000, 10000);
</pre>
<p>Also update the draw method.<br />
Now run the simulation and see how our see-saw behaves now!</p>
<p><img class="alignnone" title="See Saw" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/see-saw.png" alt="" width="100%" /></p>
<h2>Force</h2>
<p>Now what if we want to control the falling box? Maybe make it move a little, have it jump up and down, etc.<br />
To do this we need to apply force to our object. To demonstrate this we’re going to make a new class called Character that inherits from PhysicsObject.</p>
<pre class="brush: csharp; title: ;">
public class Character : PhysicsObject
    {
        public Character(PhysicsSimulator physics, Vector2 position, float width, float height, float mass, Texture2D texture)
            : base(physics, position, width, height, mass, texture)
        {
        }

        public virtual void Update(GameTime gameTime)
        {
            HandleInput(gameTime);
        }

        protected virtual void HandleInput(GameTime gameTime)
        {
            keyState = Keyboard.GetState();

            //Apply force in the arrow key direction
            Vector2 force = Vector2.Zero;
            if (keyState.IsKeyDown(Keys.Left))
            {
                force.X -= forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Right))
            {
                force.X += forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Up))
            {
                force.Y -= forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            if (keyState.IsKeyDown(Keys.Down))
            {
                force.Y += forcePower * (float)gameTime.ElapsedGameTime.TotalSeconds;
            }

            body.ApplyForce(ref force);

            oldState = keyState;
        }

        public float forcePower;
        protected KeyboardState keyState;
        protected KeyboardState oldState;

    }
</pre>
<p>As you can see force is easily applied just by constructing a force vector and calling body.ApplyForce(). We pass the vector by reference so that the garbage collector doesn’t have to jump in and act too often (since Vector2 is a value type, its normally copied each time it’s passed to a different method, don’t worry too much about that right now).<br />
You can apply impulse in the same way. (Impulse is direct, useful for jumping and explosions, while force is steadily added, more useful to make a jetpack work for example).<br />
Let’s play: in Game1 replace our box of type PhysicsObject with a box of type Character. Set box.forcePower to 1000000.  Also add box.Update(gameTime); to the Update method in Game1 and make sure the box is being drawn.<br />
If you did everything correct you should now be able to control the falling box with the arrows on your keyboard.</p>
<h2>A game character</h2>
<p>Now we’ve got all of the basics covered it’s time to talk about creating a more realistic game character. Without physics you would move an object by changing its position when a key is pressed. Jumping would be done by creating two ‘fake forces’ that sent the object up and down. When using a physics engine you shouldn’t just move your character, this will make it very hard for Farseer to handle collisions because for Farseer it looks like the character just teleported a tiny amount (there are no forces, impulses or torque present). For a realistic character we need to apply forces to a body, however this causes a problem: how much force do we apply? Do we keep applying forces (e.g. the character keeps accelerating)? This sounds very unrealistic, as a normal person quickly accelerates in just a few steps and then stays at his running speed. We could do with impulses, that instantly generate movement, however stopping the character is going to be even more problematic then. And if we encounter a slope or if the friction is not set to 0 the character will slow down until the user releases and presses the move key again.<br />
Suffice it to say that I’ve been trying all sorts of stuff for two days to get a character moving the way I want it (instant start and stop, controllable air movements, steady running speed, also characters normally don’t fall over).<br />
Luckily I came across Bryan Dismas’ blog who wrote an article on this <a href="http://amazingretardo.simiansoftwerks.com/2010/02/17/platformer-character-control-farseer-physics-engine/">http://amazingretardo.simiansoftwerks.com/2010/02/17/platformer-character-control-farseer-physics-engine/</a>. He adopted this idea from Robert Dodd (<a href="http://boxycraft.wordpress.com">http://boxycraft.wordpress.com</a>) and I’m going to change it even further.</p>
<p><img src="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/boxboy.jpg" alt="Boxboy" /><br />
<em>Image by Robert Dodd</em></p>
<p>The idea is to create a character from two parts: the upper body is just a simple rectangle. The lower body is a circle/wheel that we rotate so that we can move around and climb slopes without problems. We’re going to create a slightly simpler version of this.</p>
<ul>
<li>Upper body: a rectangle body always kept up-right using a fixed angle joint.</li>
<li>Lower body: a circle connected to the upper body using a revolute joint.</li>
</ul>
<p>With the current version of Farseer this is enough to have a nice character jumping around. So let’s write some code.<br />
Create a class called CompositeCharacter which inherits from Character.<br />
The class is fairly long because I also had to add a bit of state management to make walking, jumping and moving in-air work. However for this tutorial the most important is the overloaded method SetupPhysics that is listed here below.</p>
<pre class="brush: csharp; title: ;">
protected override void SetupPhysics(PhysicsSimulator physics, Vector2 position, float width, float height, float mass)
        {
            //Create a body that is almost the size of the entire object
            //but with the bottom part cut off.
            float upperBodyHeight = height - (width / 2);
            body = BodyFactory.Instance.CreateRectangleBody(physics, width, upperBodyHeight, mass / 2);
            //also shift it up a tiny bit to keep the new object's center correct
            body.Position = position - Vector2.UnitY * (width / 4);
            centerOffset = position.Y - body.Position.Y; //remember the offset from the center for drawing

            //Now let's make sure our upperbody is always facing up.
            fixedAngleJoint = JointFactory.Instance.CreateFixedAngleJoint(physics, body);

            //Create a wheel as wide as the whole object
            wheelBody = BodyFactory.Instance.CreateCircleBody(physics, width / 2, mass / 2);
            //And position its center at the bottom of the upper body
            wheelBody.Position = body.Position + Vector2.UnitY * (upperBodyHeight / 2);

            //These two bodies together are width wide and height high <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
            //So let's connect them together.
            motor = JointFactory.Instance.CreateRevoluteJoint(physics, body, wheelBody, wheelBody.Position);
            motor.Motor_Enabled = true;
            motor.Motor_MaxTorque = 1000f; //set this higher for some more juice
            motor.Motor_Speed = 0;

            //Create geomitries.
            wheelGeom = GeomFactory.Instance.CreateCircleGeom(physics, wheelBody, width / 2, 16);
            geom = GeomFactory.Instance.CreateRectangleGeom(physics, body, width, upperBodyHeight);

            wheelGeom.IgnoreCollisionWith(geom);
            geom.IgnoreCollisionWith(wheelGeom);

            //Set the friction of the wheelGeom to float.MaxValue for fast stopping/starting
            //or set it higher to make the character slip.
            wheelGeom.FrictionCoefficient = float.MaxValue;
        }
</pre>
<p>Quite a lot is happening here, but nothing should be really new. We first create a body that is going to be the upper part of our character, we then shift its position a bit and calculate its shift from the center. (This is handy for if we want to draw our final character). A simple fixed angle joint keeps our upper body at all times.</p>
<p>We then create the lower body (wheelBody) which is sized like a wheel just as wide as our upper body. Its center is positioned at the bottom of the upper body (see the picture above again).</p>
<p>The lower body is fixed to the upper body with a revolute joint, and because we downloaded the ‘motor’ patch we can force the lower body to rotate while it stays attached to the upper body. If you think about we’ve  just created a Segway actually.<br />
Geometries are created as usual and the upper and lower bodies are told not to collide with each other.</p>
<p>Finally we set the friction of the lower body to the highest possible value. This way the movement of our character will be very responsive. You can lower the amount of friction for a different feel (be sure to play around a bit, 0.5f gives quite a funny feel).</p>
<p>Congratulations, you’re now familiar with the basics of the Farseer physics engine. Be sure to fire up the simulation and play around a bit. Maybe try to make a more complicated level with the objects you now have.</p>
<h2>Afterthoughts</h2>
<p>You now have a bit of a grasp on the techniques that the Farseer physics engine offers you. This engine could easily be extended to make even more fun physics objects, like moving platforms. However because this is a tutorial, some things in the code have been neglected, so if you would like to extend the tutorial code, please first make sure that you make some kind of base object, of which CompositePhysicsObject and PhysicsObject extend. Then make some sort of drawing manager, this will make your life a lot easier!<br />
This tutorial has shown you a few useful tricks like Polymorphism (a Character is still a PhysicsObject) which saves writing a lot of duplicate code. Make sure that you use these techniques to the max they will make your life a lot easier!<br />
I hope you’ve enjoyed this tutorial, for more of my tutorials see <a href="http://www.roy-t.nl">www.roy-t.nl</a>.</p>
<p><strong>Download sample source</strong>: <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/roy/FarseerPlatformer.zip">FarseerPlatformer.zip</a> (under the <a href="http://www.microsoft.com/opensource/licenses.mspx#Ms-PL">MS-PL License</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-xna-farseer-platform-physics-tutorial/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Article: Rolling World Tutorial</title>
		<link>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/</link>
		<comments>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/#comments</comments>
		<pubDate>Wed, 08 Sep 2010 21:01:46 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[2D]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Christian Schlager]]></category>
		<category><![CDATA[Content Creation]]></category>
		<category><![CDATA[Rolling World]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1745</guid>
		<description><![CDATA[by Christian Schlager



When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Christian Schlager</h4>
<div align="center">
<img width="60%" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/gfx/aerial_perspective_in_game.jpg">
</div>
<p>When you look around the XBox Indie Games Channel, there aren't a lot of  3D games around. Most XNA games only feature 2D graphics. I hope to  contribute with this tutorial to making 3D graphics a bit less  intimidating. And maybe the little prototype we will create throughout  the next pages will be the starting point of a great 3D indie game by  one of you <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>We will make a prototype that features the kind of rolling world effect  that you can see in games such as Animal Crossing or DeathSpank. We will  also create the textures and 3D models that go along with the rolling  effect and recreate the combination of 2D art with a 3D world you can  see in the game DeathSpank.<br />
<span id="more-1745"></span></p>
<h4>Difficulty</h4>
<p>This tutorial is intended for Beginner/Intermediate developers.<br />
If you played around with XNA and /or worked on 2D games before this tutorial should be no problem for you.</p>
<h4>Content</h4>
<p>The first section of this tutorial covers the creation of the assets for our game.<br />
We will draw textures for the world, for the trees and a very simple one for the hero.<br />
We will also create a simple DirectX effect file which we will use to render the models we create in SoftImage Mod Tool.<br />
Once we have all the assets we will set up our game project in Visual  Studio, load and render game objects and then move the hero of our game  around.<br />
In the last section we will add the rolling world effect. We will  develop a concept of the effect with sketches and pseudo-code and then  implement the effect.<br />
Finally, there is some bonus content you might try once you are done with the tutorial.<br />
This tutorials comes with pre-made assets in case you are only  interested in the programming side of the tutorial. You can also skip  the foreplay completely and jump to the rolling world effect part using  the project in the folder WorldGame.<br />
You can also explore for yourself with the complete rolling world game in the folder RollingWorldGame.</p>
<h4>Software</h4>
<dl>
<dt>Visual C# 2008 Express</dt>
<dd>The Visual Studio 2008 Express is a free set of tools for developing applications for Windows.<br />
<a href="http://www.microsoft.com/express/Downloads/#2008-Visual-CS" target="new">Download Visual C\# 2008 Express</a> </dd>
<dt>XNA Game Studio 3.1</dt>
<dd>This software package contains the XNA framework which includes an  extensive set of class libraries specific to game development. Once you  installed the Game Studio you can use it in Visual Studio:<br />
<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=80782277-d584-42d2-8024-893fcd9d3e82" target="new">Microsoft XNA Game Studio 3.1</a> </dd>
<dt>Paint.NET</dt>
<dd>Paint.NET is free image and photo editing software for Windows. We will use it to create textures for our game:<br />
<a href="http://www.getpaint.net/download.html" target="new">Download Paint.NET</a> </dd>
<dt>SoftImage Mod Tool</dt>
<dd>We will be using Autodesk SoftImage Mod Tool to create the 3D  models. The version we will use is for non-commercial use only which is  fine for this tutorial:<br />
<a href="http://usa.autodesk.com/adsk/servlet/pc/item?siteID=123112&amp;id=13571320" target="new">Download Autodesk Softimage Mod Tool</a></dd>
</dl>
<h4>Feedback</h4>
<p>My name is Christian Schlager and I wrote this tutorial. If you like it,  have constructive feedback or found a mistake in the tutorial please  leave a comment here, or on my page: <a href="http://googoobachoo.blogspot.com/2010/08/rolling-world-tutorial.html" target="new">http://googoobachoo.blogspot.com</a></p>
<h2>Downloads</h2>
<p>This tutorial is accompanied by the following downloads:</p>
<p><a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/WorldGame.zip">WorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/RollingWorldGame.zip">RollingWorldGame.zip</a><br />
<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/rollingworld/Assets.zip">Assets.zip</a></p>
<h4>Next Page: Creating the assets</h4>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/09/article-rolling-world-tutorial/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

