<?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; Collision</title>
	<atom:link href="http://www.sgtconker.com/category/xna/collision/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>Placing a tank on a planet</title>
		<link>http://www.sgtconker.com/2010/01/placing-a-tank-on-a-planet/</link>
		<comments>http://www.sgtconker.com/2010/01/placing-a-tank-on-a-planet/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 22:29:12 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[Collision]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[Dave Carlile]]></category>
		<category><![CDATA[Procedural Geometry]]></category>
		<category><![CDATA[Tank]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=970</guid>
		<description><![CDATA[As part of his Procedural Planets series, Dave takes a break from generating and rendering a planet and instead tried to place a tank on the surface of the generated planet. Read about the whole implementation process on his blog.
]]></description>
			<content:encoded><![CDATA[<p>As part of his Procedural Planets series, Dave takes a break from generating and rendering a planet and instead tried to place a tank on the surface of the generated planet. Read about<a href="http://www.crappycoding.com/2010/01/of-tanks-and-quad-trees/"> the whole implementation process</a> on his blog.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/01/placing-a-tank-on-a-planet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More 2D collisions</title>
		<link>http://www.sgtconker.com/2010/01/more-2d-collisions/</link>
		<comments>http://www.sgtconker.com/2010/01/more-2d-collisions/#comments</comments>
		<pubDate>Sun, 10 Jan 2010 07:59:20 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Collision]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[George Clingerman]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[Physics]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=899</guid>
		<description><![CDATA[After Glenn's Rotated Per Pixel Collision, George "good MVP that everyone likes" Clingerman just released a new sample that shows how to use the Separating Axis Theorem to implement 2D Rotated Rectangle Collision. Read all about it on his site.

]]></description>
			<content:encoded><![CDATA[<p>After Glenn's <a href="http://www.sgtconker.com/2010/01/rotated-per-pixel-collision/">Rotated Per Pixel Collision</a>, George "good MVP that everyone likes" Clingerman just released a new sample that shows how to use the Separating Axis Theorem to implement 2D Rotated <strong>Rectangle</strong> Collision. <a href="http://www.xnadevelopment.com/tutorials/rotatedrectanglecollisions/rotatedrectanglecollisions.shtml">Read all about it on his site</a>.</p>
<p><a href="http://www.xnadevelopment.com/tutorials/rotatedrectanglecollisions/rotatedrectanglecollisions.shtml"><img class="aligncenter" title="rotated rectangle collision" src="http://www.xnadevelopment.com/livewriter/XNA.comNewsampleon2DRotatedRectangleColl_70A9/rotatedrectangle.png" alt="" width="200" height="150" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/01/more-2d-collisions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article : Spatial hashing implementation for fast 2D collisions</title>
		<link>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/</link>
		<comments>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:19:06 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[A.I]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Collision]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[SPATIAL HASHING]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=21</guid>
		<description><![CDATA[This article describes how to use a spatial hashing implementation to speed up collisions in your games.]]></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 a spatial hashing implementation to speed up collisions in your games.</p>
<p>This is a sample prototype I wrote to fix a performance limitation with collision checking in my game.<br />
So what is spatial hashing? Here is a good 1 liner I will borrow from the source material i used.</p>
<p><span id="more-21"></span></p>
<p>“Spatial hashing is a process by which a 3D or 2D domain space is projected into a 1D hash table.” <a href="http://www.cs.ucf.edu/~jmesit/publications/scsc%202005.pdf" target="_blank">Optimization of Large-Scale, Real-Time Simulations by Spatial Hashing</a></p>
<p>So why do we need it?</p>
<p>Well, for me it was a problem in my collision code and my A.I code which was trying to find nearby objects to check collisions for. Due to my brute force nature if I had 10 monsters in the world there would be 10*10 = 100 collision checks in every update. Now ramp the number up to 100 to be a bit excessive and we end up with 100*100=10,000 collision checks. This makes the cpu cry like a little baby as I’m sure you can imagine.<br />
To rectify this we need to reduce the amount of collision checks we need to do in the first place.<br />
This is where spatial hashing comes in handy.</p>
<p>Imagine the game world in a flat 2d grid. 100 by 100 pixels and each cell was 25 by 25 pixels. Now number the cells from left to right, top to bottom 0 onwards.<br />
You will end up with something like this. The orange circles are the game objects, in my case, monsters.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/image.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/06/image_thumb.png" border="0" alt="image" width="162" height="150" /><br />
</a></p>
<p>Each cell is a bucket of game objects and a unique hash id. If we imagine the bucket as a list of 16 buckets, 0-15 cells and placed the game objects in that bucket.<br />
It might look something like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/image1.png"><br />
<img style="display:inline;border-width:0;" title="image" src="http://conkerjo.files.wordpress.com/2009/06/image_thumb1.png" border="0" alt="image" width="60" height="244" /></a></p>
<p>This is our 1D grid mentioned in the introduction.</p>
<p>It’s a simple premise really, any item in bucket 3 for example, cannot possibly collide with something in bucket 9.<br />
This reduces the amount of times we need to cycle the nearby objects but also dramatically reduce the amount of times we need to check if a collision is happening.</p>
<p>Ok, so the above implementation is fine as long as a game object only ever exists in 1 bucket. But what if it crosses a line and exists in more than 1 bucket.<br />
To resolve this I imagined a box around each game object, and I calculated the hash id for each corner of the box.<br />
I then populate a List; going through each bucket the game object is in. Sounds simple ?</p>
<p>Let me show you some of this theory in code.</p>
<p>First we need a game object. For this sample all we need is a position and a radius.</p>
<pre class="brush: csharp; title: ;">
    public class GameObject
    {
        public Vector2 Position { get; set; }
        public float Radius { get; set; }
    }
	</pre>
<p>We create a new class to store the grid data in including the buckets. I’m terrible at naming classes so I called it SpatialManager.<br />
I gave this class a Setup method which takes a full scenewidth, height and a cellsize. In our example this would be 100,100,25</p>
<pre class="brush: csharp; title: ;">
    public void Setup(int scenewidth, int sceneheight, int cellsize)
    {
</pre>
<p>We can work out how many buckets we need by first calculating the rows and cols then simply create a new Dictionary of buckets to the tune of Rows*Cols.<br />
I also store these variables passed in for future use.</p>
<pre class="brush: csharp; title: ;">
    Cols= scenewidth / cellsize;
    Rows= sceneheight / cellsize;
    Buckets = new Dictionary&amp;lt;int, List&amp;lt;GameObject&amp;gt;(Cols * Rows);

    for (int i = 0; i &amp;amp;lt; Cols*Rows; i++)
    {
        Buckets.Add(i, new List());
    }

    SceneWidth = scenewidth;
    SceneHeight = sceneheight;
    CellSize = cellsize;
}
</pre>
<p>Each update, we need to clear out the buckets and re calculate the buckets each game object are in. I created a method called ClearBuckets to start fresh.</p>
<pre class="brush: csharp; title: ;">
   internal void ClearBuckets()
   {
       Buckets.Clear();
       for (int i = 0; i &amp;amp;lt; Cols * Rows; i++)
       {
           Buckets.Add(i, new List());
       }
   }</pre>
<p>We now need a method to register a game object into the buckets it sits in.</p>
<pre class="brush: csharp; title: ;">
    internal void RegisterObject(GameObject obj)
    {
        List cellIds= GetIdForObj(obj);
        foreach (var item in cellIds)
        {
            Buckets[item].Add(obj);
        }
    }
</pre>
<p>As you can see, the code retrieves a list of cellids to add the game object to.</p>
<p>In the GetIdForObj method it calculates the cell id for each corner of the game object.</p>
<p>If we were just checking the position of the game object the calculation would be.</p>
<pre class="brush: csharp; title: ;">
    float width = SceneWidth / CellSize; // 100 / 25
    int hashid=(int)(
    (Math.Floor(position.X / CellSize)) +
    (Math.Floor(position.Y / CellSize)) * width);
	</pre>
<p>We need to do this for each corner and add our game to each bucket.</p>
<p>The GetIdForObj method looks like this.</p>
<pre class="brush: csharp; title: ;">
    private List GetIdForObj(GameObject obj)
    {
        List bucketsObjIsIn = new List();

        Vector2 min = new Vector2(
            obj.Position.X - (obj.Radius),
            obj.Position.Y - (obj.Radius));
        Vector2 max = new Vector2(
            obj.Position.X + (obj.Radius),
            obj.Position.Y + (obj.Radius));

        float width = SceneWidth / CellSize;
        //TopLeft
        AddBucket(min,width,bucketsObjIsIn);
        //TopRight
        AddBucket(new Vector2(max.X, min.Y), width, bucketsObjIsIn);
        //BottomRight
        AddBucket(new Vector2(max.X, max.Y), width, bucketsObjIsIn);
        //BottomLeft
        AddBucket(new Vector2(min.X, max.Y), width, bucketsObjIsIn);

	return bucketsObjIsIn;
    }
</pre>
<p>And here is the AddBucket method which uses the calculation described above and adds it to the list of bucket id's to add to.</p>
<pre class="brush: csharp; title: ;">
    private void AddBucket(Vector2 vector,float width,List buckettoaddto)
    {
        int cellPosition = (int)(
                   (Math.Floor(vector.X / CellSize)) +
                   (Math.Floor(vector.Y / CellSize)) *
                   width
        );
        if(!buckettoaddto.Contains(cellPosition))
            buckettoaddto.Add(cellPosition);

    }
</pre>
<p>Now that we have our grid of buckets. It's a very simple retrieval process. I added a method to get the nearby objects of a given object. This uses the GetIdForObj method and populates a list of GameObject's and returns once complete. This is the key part to this solution, you only now need to check items which are actually nearby and not items the other side of the theoretical world.</p>
<pre class="brush: csharp; title: ;">
    internal List GetNearby(GameObject obj)
    {
        List objects = new List();
        List bucketIds = GetIdForObj(obj);
        foreach (var item in bucketIds)
        {
            objects.AddRange(Buckets[item]);
        }
        return objects;
    }
</pre>
<p>So that’s it. Now you can do your normal collision checking by retrieving nearby GameObjects. And here’s a screenshot to prove it.</p>
<p>I’ve placed my mouse over one of the GameObjects and it’s highlighted all nearby items. Notice how they cross over cells. This is because the item i hover over is on the line and exists in multiple cells. Also notice the amount of checks it has to do. For brute force it has to do 250,000 bounding box collision checks. For spatial hashing, it checks only 4840 times. Wicked.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/06/spatialhashing.png"><img style="display:inline;border-width:0;" title="SpatialHashing" src="http://conkerjo.files.wordpress.com/2009/06/spatialhashing_thumb.png" border="0" alt="SpatialHashing" width="468" height="367" /></a></p>
<p>And what would a sample be without source code?</p>
<p>Enjoy</p>
<p><a href="http://conkerjoe.ziggyware.com/wm/SpatialTest.zip" target="_blank">Link To Sample</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/spatial-hashing-implementatio-for-fast-2d-collisionsplaceholder/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

