<?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>Game Code SchoolGame Code School -  &#187; Essentials</title>
	<atom:link href="https://gamecodeschool.com/category/essentials/feed/" rel="self" type="application/rss+xml" />
	<link>https://gamecodeschool.com</link>
	<description>Game Coding for Beginners</description>
	<lastBuildDate>Wed, 29 Jan 2025 11:28:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Collision detection: Irregular polygons (Asteroids) using the crossing number algorithm</title>
		<link>https://gamecodeschool.com/essentials/collision-detection-crossing-number/</link>
		<comments>https://gamecodeschool.com/essentials/collision-detection-crossing-number/#comments</comments>
		<pubDate>Thu, 02 Jun 2016 10:20:28 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Essentials]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=13398</guid>
		<description><![CDATA[Testing for collision with an irregular polygon is the exact same problem as if you were doing collision detection for an Asteroids game clone. If you don&#8217;t know what Asteroids is you can learn about it here. As this helps us visualize the problem I will present this whole tutorial in those terms. This collision [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Testing for collision with an irregular polygon is the exact same problem as if you were doing collision detection for an Asteroids game clone. If you don&#8217;t know what Asteroids is you can learn about it <a href="https://en.wikipedia.org/wiki/Asteroids_(video_game)">here</a>. As this helps us visualize the problem I will present this whole tutorial in those terms. This collision detection method is much more complex than the previous methods we have discussed. So be sure to read all the articles in the Recommended preparation tutorials section above. Also make sure you are comfortable with OOP in either <a href="http://gamecodeschool.com/c-plus-plus/introduction-to-oop-for-c_plus_plus-games/">C++</a> or <a href="http://gamecodeschool.com/java/understanding-oop-for-coding-java-games/">Java</a>.</p>
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-1 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this tutorial</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to read: 10 minutes</p>
<h4>New Concepts:</h4>
<ol>
<li>Collision detection with irregular polygons</li>
<li>Crossing number algorithm</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/">Rectangle intersect collision detection</a></li>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-radius-overlap/">Radius overlap collision detection</a></li>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-neighbour-checking/">Neighbour checking collision detection</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Projects related to or that demonstrate these concepts</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>None yet <img src="https://gamecodeschool.com/wp-includes/images/smilies/frownie.png" alt=":-(" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>It doesn&#8217;t have to be hard work, however. What we need to do is take a moment to consider a strategy that will work for us. This tutorial will focus on the code rather than an explanation of the math. Understanding the math relies on an understanding of Trigonometry, in particular sine and cosine functions. If this interests you you could start with <a href="http://gamecodeschool.com/essentials/calculating-heading-in-2d-games-using-trigonometric-functions-part-1/">Using trigonometric functions in 2d games</a>.<br />
The code samples are in Java because it was Java that I implemented it in a game. Also, because there appears to be very few Java examples on the Web but already a few C++ do exist although I haven&#8217;t seen any that talk through the stages of adding it to an actual game.</p>
<p>Apart from the class syntax and the member variable access specifiers during declaration (public, private, whatever) there would be virtually no changes between the Java or C++ code. There will obviously be a difference between some of the method/function names and the classes/libraries you will need to import/#include.</p>
<h2>Planning for irregular polygon collision detection</h2>
<p>What we want to know is when a point from another object(we will focus on the points of the triangle shaped ship) goes inside the asteroid. It is not enough to just detect an intersection because this is ambiguous with rotating irregular polygons.</p>
<p>Although we will not be detecting any asteroid on asteroid collisions in this tutorial, as you will see when our collision detection nears completion, achieving asteroid on asteroid collision detection would not present much of an extra challenge. It would, however, put an extra strain on the device&#8217;s CPU. In addition, once you get this system working, it will be trivial to implement bullet (single vertex) collision with an asteroid.</p>
<h3>Colliding with an asteroid</h3>
<p>We need to find out if any single vertex from the ship crosses into the space contained by the vertices of the asteroid. An additional problem is that the asteroid is not only a moving target but also a rotating one. We will not only have to rotate and translate all the vertices of the objects but the asteroids as well. We don&#8217;t want to do this every frame.</p>
<div class="fusion-alert alert notice alert-dismissable alert-warning alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-lg fa-cog"></i></span> If you are using a library you might be able to simplify the code by obtaining the coordinates of the rotated vertices from this library. This tutorial will assume you are not and show you how to compute them. Remember that if you are using OpenGL or OpenGL ES then OpenGL will conveniently rotate and draw all your asteroids and other objects as part of your drawing code. It will not, unfortunately, give you the rotated vertex locations back for your own use.</div>

<p>Being more specific, we need to calculate any vertex of the ship crossing the line made between each pair of vertices on the asteroid. The first problem, as already mentioned is, that detecting the intersection of a point is ambiguous with a rotating irregular polygon.</p>
<p>Fortunately at this point we can fall back on a clever and simple algorithm, devised and refined by mathematicians far greater than myself.</p>
<div class="fusion-alert alert custom alert-dismissable alert-custom alert-shadow" style="background-color:;color:;border-color:;border-width:1px;">
  <button style="color:;border-color:;" type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-comments-o"></i></span>Actually I am a terrible mathematician and usually rely on my son to explain high school level concepts to me. So if I can get this working then you can to.</div>

<p>We will use the Crossing Number algorithm. Here is how it works.</p>
<h3>The Crossing Number algorithm</h3>
<p>We compute the line made by a pair of vertices and use conventional trigonometry to see if a particular vertex from the object being tested crossed that line. If it did we increment a variable from 0 to 1. Next, we test the same point against each and every line made by each vertex pair from an asteroid, incrementing our variable each time it does. If after testing the vertex against every line, using the crossing number algorithm our variable is <strong>odd, we have a hit</strong>. If it is even, no collision has occurred.</p>
<p>Of course, if no collision has occurred we must proceed to test each and every vertex from the object being tested against each and every line formed out of the vertex pairs on the asteroid. Here is a visual representation of the crossing number algorithm in action.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2016/06/how-crossing-number-algorithm-works.png"><img class="aligncenter size-full wp-image-13408" src="http://gamecodeschool.com/wp-content/uploads/2016/06/how-crossing-number-algorithm-works.png" alt="crossing number algorithm" width="702" height="702" /></a></p>
<p>Notice in the previous image that all the cases where the vertex is inside the asteroid, the value is odd.</p>
<p>With complex calculations going on we will definitely want to do a simple first-phase test to see if it is likely there has been a collision, before doing the complex tests.</p>
<h3>The steps and overview of asteroid collision detection</h3>
<p>The <a href="http://gamecodeschool.com/essentials/collision-detection-radius-overlap-method/">radius overlap</a> test is quite appropriate when testing a single vertex like a bullet, a spinning triangle like a ship or indeed a rotating asteroid. With this in mind, here is an overview of the whole process we will use for testing for collisions between asteroids:</p>
<ol>
<li>Has the radius of the ship overlapped with the radius of an asteroid?</li>
<li>If yes has the first vertex of the object crossed the first line of the asteroid</li>
<li>if yes <pre class="crayon-plain-tag">crossingNumber ++</pre></li>
<li>Repeat step 2 with each line on the object</li>
<li>If <pre class="crayon-plain-tag">crossingNumber</pre> is odd return true to calling code because a collision has occurred.</li>
<li>If <pre class="crayon-plain-tag">crossingNumber</pre> is even no collision has occurred(yet) repeat steps 2, 3 and 4 with the next vertex of the object being tested.</li>
<li>If all vertices have been tested and we have reached here then no collision has occurred</li>
</ol>
<p>Game programming patterns are beyond the scope of this tutorial so I want to present an object-oriented solution that is simple to grasp and easily adapted. We will set up a collision detection class called <pre class="crayon-plain-tag">CD</pre>. It will have a <pre class="crayon-plain-tag">detect()</pre> method that will test for collisions with asteroids and will be called for the ship against each and every asteroid each frame.</p>
<p>Doing the calculations outside of the objects themselves means we will need a whole bunch of data about the objects we will be testing, made accessible to our new <pre class="crayon-plain-tag">CD</pre> class.</p>
<h2>Coding a collision detection solution for irregular polygons in C++ or Java</h2>
<p>The first class we will call <pre class="crayon-plain-tag">CollisionPackage</pre>. So we know we need a certain set of data to do our detections properly. This class will hold all the data that our collision detection class will need. Every object that we need to detect collisions (asteroids and ship) will have an <pre class="crayon-plain-tag">CollisionPackage</pre> instance.</p>
<p>When the time comes to rotate all the points to their real world location, our collision package will need to know which way the object is facing. For this we have a float called <pre class="crayon-plain-tag">facingAngle</pre>.</p>
<div class="fusion-alert alert notice alert-dismissable alert-warning alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-lg fa-cog"></i></span>Note that we do not need to rotate every vertex for every frame of the game.</div>

<p>We will need a copy of the un-rotated model space vertices. We will not go to the trouble of updating these every frame and will do so only after the first phase of collision detection shows a collision is likely/possible. We will also hold a pre-computed value for the length of the array that holds these vertices. It can potentially save time in the collision detection process.</p>
<p>Therefore, we will also need the world coordinates of the object. This is a single point in the centre of the object. This we will update every frame. Each object will have a pre-computed <pre class="crayon-plain-tag">radius</pre> variable which is the size of the object from its centre to its furthest vertex. This will be used in our <pre class="crayon-plain-tag">detect()</pre> method to do the radius overlapping, phase one detection.</p>
<div class="fusion-alert alert notice alert-dismissable alert-warning alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-lg fa-cog"></i></span>In the code we use <pre class="crayon-plain-tag">PointF</pre> objects from the Android API these could easily be swapped out for <a href="http://gamecodeschool.com/blog/what-is-sfml-and-should-i-use-it/">SFML</a> <pre class="crayon-plain-tag">Vector2f</pre> or your own simple Point class.</div>

<p>We will also have a couple of <pre class="crayon-plain-tag">PointF</pre> objects, <pre class="crayon-plain-tag">currentPoint</pre> and <pre class="crayon-plain-tag">currentPoint2</pre> which are just handy objects that will hold the vertices currently being tested.</p>
<h3>The CollisionPackage class</h3>
<p>Create a new class, call it CollisionPackage and implement the members we have just discussed.</p>
<pre class="brush: java; title: ; notranslate">
/*
	All objects which can collide have a collision package.
	Asteroids, ship, bullets. The structure seems like slight
	overkill for bullets but it keeps the code generic,
	and the use of vertexListLength means there isn't any
	actual speed overhead. Also if we wanted line, triangle or
	even spinning bullets the code wouldn't need to change.
*/

public class CollisionPackage {

    /*
		All the members are public to avoid multiple calls
		to getters and setters.

		The facing angle allows us to calculate the
		current world coordinates of each vertex using
		the model-space coordinates in vertexList.
	*/
    public float facingAngle;

    // The model-space coordinates
    public PointF[] vertexList;

    /*
		The number of vertices in vertexList
		is kept in this next int because it is pre-calculated
		and we can use it in our loops instead of
		continually calling vertexList.length.
	*/
    public int vertexListLength;

    // Where is the centre of the object?
    public PointF worldLocation;

    /*
		This next float will be used to detect if the circle shaped
		hitboxes collide. It represents the furthest point
		from the centre of any given object.
		Each object will set this slightly differently.
		The ship will use height/2 an asteroid will use
		whatever the max length of a line can be.
		This tutorial doesn't cover randomly generating
		the asteroid vertices. For this tutorial, 25
		is assumed. As long as the real length isn't greater
		the value will work for you to.
	*/
    public float radius;

    // A couple of points to store results and avoid creating new
    // objects during intensive collision detection
    public PointF currentPoint = new PointF();
    public PointF currentPoint2 = new PointF();
</pre>
<p>Next, in the same class, we have a simple constructor that will receive all the necessary data from each object at the end of each object&#8217;s constructor. Implement the <pre class="crayon-plain-tag">CollisionPackage</pre> constructor as shown. The code implies that your class (ship/asteroid/whatever) needs to be able to supply the necessary data for the arguments when you call it.</p>
<pre class="brush: java; title: ; notranslate">
public CollisionPackage(
	PointF[] vertexList,
	PointF worldLocation,
	float radius,
	float facingAngle){
	vertexListLength = vertexList.length;

   this.vertexList = new PointF[vertexListLength];

	// Make a copy of the array
	for (int i = 0; i &lt; vertexListLength; i++) {
		this.vertexList[i] = new PointF();
		this.vertexList[i].x = vertexList[i].x;
		this.vertexList[i].y = vertexList[i].y;
	}

   this.worldLocation = new PointF();
   this.worldLocation = worldLocation;
   this.radius = radius;
   this.facingAngle = facingAngle;

}// End constructor

}// End class
</pre>
<p>That&#8217;s all the data we need to do our advanced collision detection.</p>
<h3>Adding collision packages to the game objects</h3>
<p>Add a new member of the type <pre class="crayon-plain-tag">CollisionPackage</pre> to each class that you want to detect collisions with asteroids, including the asteroids themselves. Also, add an array of <pre class="crayon-plain-tag">PointF</pre> objects called <pre class="crayon-plain-tag">points</pre> and the other variables your class will need to call the <pre class="crayon-plain-tag">CollisionPackage</pre> constructor. A common mistake is to initialize the <pre class="crayon-plain-tag">points</pre> array with world space coordinates. They must be model space coordinates and the world space coordinates will be calculated, when necessary, from the model space and <pre class="crayon-plain-tag">worldLocation</pre>.</p>
<pre class="brush: java; title: ; notranslate">
// Inside Ship, Asteroid, Whatever class
CollisionPackage cp;

// Next, a 2d representation using PointF of
// the vertices. Used to build shipVertices
// and to pass to the CollisionPackage constructor
PointF[] points;
PonitF worldLocation;
float radius;
float facingAngle;

/*
	Your code to initialize the points array,
	location and angle of your ship goes here.
	This will vary depending upon how your game is implemented
	Initialize the above variables to represent your ship/object
	...
	...
	...
*/
</pre>
<p>It is possible that a vertex from the asteroid might sneak inside the ship. Remember that we will only be testing for vertices from the ship entering the asteroid. This next image shows the problem.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2016/06/crossing-number-shortfalls.jpg"><img class="aligncenter size-full wp-image-13412" src="http://gamecodeschool.com/wp-content/uploads/2016/06/crossing-number-shortfalls.jpg" alt="Vertex from asteroid intersects with ship undetected" width="640" height="445" /></a></p>
<p>We could completely solve this problem by testing all the asteroids vertices against all of the ship&#8217;s lines as well as what we are planning to do (testing all the ship&#8217;s vertices against all the asteroids lines). This would slow the game down.</p>
<p>For this reason, it might also be worth adding three extra model space coordinates to the ship. Your drawing code does not need to know about these. They are positioned in the middle of each of the three lines which make the ship. We do this to make it harder for a vertex of an asteroid to drift inside the ship without a vertex of the ship being inside the asteroid. Just adding a few extra points to the ship does produce near-perfect detection as shown next.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2016/06/crossing-number-shortfalls-solution.jpg"><img class="aligncenter size-full wp-image-13413" src="http://gamecodeschool.com/wp-content/uploads/2016/06/crossing-number-shortfalls-solution.jpg" alt="crossing-number-shortfalls-solution" width="640" height="440" /></a></p>
<p>Now our object has been initialized we can initialize the collision package.</p>
<h3>Creating a CollisionPackage for the ship</h3>
<p>Here is how the code might look in the constructor of the class that represents a ship. Be sure to read the comments too.</p>
<pre class="brush: java; title: ; notranslate">
// Initialize the collision package
// The code assumes you have
// initialized points, worldLocation, radius and facingAngle

cp = new CollisionPackage(
	points,
	worldLocation,
	radius,
	facingAngle);
</pre>
<h3>Creating the CollisionPackage for the asteroid</h3>
<p>As stated, we will also need a collision package in the class that represents an asteroid. Use the exact same steps above. Obviously, the way that you decide the model space coordinates and location in the world is specific to your implementation. As long as you have an initialized <pre class="crayon-plain-tag">CollisionPackage</pre>, called <pre class="crayon-plain-tag">cp</pre>, the rest of the tutorial will work. There is one BIG gotcha to be aware of!</p>
<div class="fusion-alert alert error alert-dismissable alert-danger alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-exclamation-triangle"></i></span>We will test the vertices of the ship against the lines of an asteroid. Therefore you must add an extra vertex to the points array for the asteroid. All you do is repeat the first vertex at the end. This way, the collision detection code will be able to test the line between the last vertex and the first.</div>

<h3>Synchronise the collision package each frame</h3>
<p>The code in the update section of your game objects (ship/asteroid/whatever) would look like this. Notice we do not do anything with the array of vertices.</p>
<pre class="brush: java; title: ; notranslate">
// Update the collision package
cp.facingAngle = facingAngle;
cp.worldLocation = WorldLocation;
</pre>
<p>Now we can code the actual collision detection.</p>
<h2>The CD (Collision Detection) class</h2>
<p>What we will do now is implement the first phase of collision detection. As we have discussed, the algorithms we will use are computationally expensive and we only want to use them when there is a realistic chance of a collision. For this reason, we will check the ship against every asteroid using the radius overlapping method. You could go further than this tutorial and implement <a href="http://gamecodeschool.com/essentials/collision-detection-neighbour-checking/">neighbour checking</a> before this as well.</p>
<p>These first checks will decide whether we then move on to do the more accurate and computationally expensive checks. We will implement these second phase checks a bit later, which will use more advanced algorithms and put the data in our collision packages to full use.</p>
<p>To get started create a new class and call it <pre class="crayon-plain-tag">CD</pre>. Add a member <pre class="crayon-plain-tag">PointF</pre> object and initialize it. We will use it to avoid creating new objects during the critical parts of the code.</p>
<pre class="brush: java; title: ; notranslate">
private static PointF rotatedPoint = new PointF();
</pre>
<p>Now for the method.</p>
<h3>Implementing radius overlapping for asteroids and ship</h3>
<p>Let&#8217;s add our method to the <pre class="crayon-plain-tag">CD</pre> class to detect collisions between the ship and asteroids. As we discussed, we are only implementing the first part of this method for now. Here is the implementation of the radius overlapping code.</p>
<p>The code works by making a virtual triangle with a missing side and then using Pythagoras&#8217; theorem to calculate the missing side, which is the distance between the centre points of the two objects. Then if the combined radii of the two objects are greater than the distance between the two object centres we have an overlap.</p>
<p>Add the <pre class="crayon-plain-tag">detect()</pre> method with the radius overlapping code. Notice we <pre class="crayon-plain-tag">return true</pre> if the radii overlap. This one line of code will be replaced with the more accurate detection code in a minute.</p>
<pre class="brush: java; title: ; notranslate">
public static boolean detect(
	CollisionPackage cp1,
	CollisionPackage cp2) {

	boolean collided = false;

	// Check circle collision between the two objects

	// Get the distance of the two objects from
	// the centre of the circles on the x axis
	float distanceX = (cp1.worldLocation.x)
		- (cp2.worldLocation.x);

	// Get the distance of the two objects from
	// the centre of the circles on the y axis
	float distanceY = (cp1.worldLocation.y)
		- (cp2.worldLocation.y);

	// Calculate the distance between the center of each circle
	double distance = Math.sqrt(
		distanceX * distanceX + distanceY * distanceY);

	// Finally, see if the two circles overlap
	// If they do it is worth doing the more intensive
	// and accurate check.
	if (distance &lt; cp1.radius + cp2.radius) {

		// todo  Eventually we will add the
		// more accurate code here
		// todo and delete the line below.
		collided = true;
	}

	return collided;
}
</pre>
<p>Now we can test for the ship hitting an asteroid, although only with radius overlapping method.</p>
<div class="fusion-alert alert error alert-dismissable alert-danger alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-exclamation-triangle"></i></span>Get your game working with this simple code so far! If you have bugs or typos, it will be MUCH easier to fix them before we add the rest of the code!</div>

<p>Your code in the update part of the main game loop to check an array full of asteroid objects against an object called ship, might look something like this next code.</p>
<pre class="brush: java; title: ; notranslate">
// Check collisions between asteroids and ship
// Loop through each asteroid in turn

for (int asteroidNum = 0;
	asteroidNum &lt; numAsteroids;
	asteroidNum++) {

	/*
		In a real game you might have a way to
		check whether a specific asteroid is
		currently active before testing
		No point doing anything if asteroid blew up last frame
	*/

	// Perform the collision checks by
	// passing in the collision packages
	if (CD.detect(ship.cp, asteroids[asteroidNum].cp)) {

		// hit!
		// What happens here is specific to your game
	}

}
</pre>
<p>At this point, you could play your game and our rudimentary collision detection will work. But fly too close to an asteroid and you will lose a life without actually needing to touch it. We want to be able to skim the surface of an asteroid and only get a hit when a point actually crosses into the exact space of another object.</p>
<h3>Precise collision detection with asteroids</h3>
<p>Once we have rotated and translated the asteroid&#8217;s vertices we will need to handle them in pairs of vertices that each forms a line. It is these lines that we will test against each and every vertex from the spaceship. This test will enable us to use our crossing number algorithm which we have discussed.<br />
We need to do all of this within the body of the</p>
<pre class="brush: java; title: ; notranslate">
if (distance &lt; cp1.radius + cp2.radius) { ...}
</pre>
<p>where we previously just returned true.</p>
<p>There is quite allot of code so we will split it into chunks so we can see what is going on at each stage. Also, the code indentation will not always be consistent from block to block. This is so the format is in the most readable way possible for a web page. The next few blocks of code are the entire contents of the aforementioned if block that needs replacing.</p>
<div class="fusion-alert alert success alert-dismissable alert-success alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-check-circle"></i></span>We could use a sine &amp; cosine look-up table here instead of keep calling the methods. The performance gain from look-up tables isn&#8217;t guaranteed, however, and research and testing for your specific situation is a good idea.</div>

<p>Before we jump into the <pre class="crayon-plain-tag">for</pre> loops, we will compute a few things that won&#8217;t change for the duration of this method. The sine and cosine of the facing angle from each of the two collision packages.</p>
<pre class="brush: java; title: ; notranslate">
if (distance &lt; cp1.radius + cp2.radius) {

	// todo  Eventually we will add the
	// more accurate code here
	// todo and delete the line below.
	// collided = true;

	double radianAngle1 = ((cp1.facingAngle / 180) * Math.PI);
	double cosAngle1 = Math.cos(radianAngle1);
	double sinAngle1 = Math.sin(radianAngle1);

	double radianAngle2 = ((cp2.facingAngle / 180) * Math.PI);
	double cosAngle2 = Math.cos(radianAngle2);
	double sinAngle2 = Math.sin(radianAngle2);

	int numCrosses = 0; // The number of times we cross a side

	float worldUnrotatedX;
	float worldUnrotatedY;
</pre>
<p>Now we loop through all the vertices from <pre class="crayon-plain-tag">cp2</pre> then test each in turn with all the sides (vertex pairs) from <pre class="crayon-plain-tag">cp1</pre>. Remember an asteroid has an extra vertex of padding which is the same as the first. So we can test the last side/line of the asteroid. So we must always pass in the asteroid collision package as the SECOND argument when calling <pre class="crayon-plain-tag">CD.detect()</pre>.</p>
<p>In the next block of code, we translate then rotate the object being tested against an asteroid.</p>
<pre class="brush: java; title: ; notranslate">
for (int i = 0; i &lt; cp1.vertexListLength; i++) {

	worldUnrotatedX = cp1.worldLocation.x + cp1.vertexList[i].x;
	worldUnrotatedY = cp1.worldLocation.y + cp1.vertexList[i].y;

	// Now rotate the newly updated point, stored in currentPoint
	// around the centre point of the object (worldLocation)
	cp1.currentPoint.x = cp1.worldLocation.x +
		(int) ((worldUnrotatedX - cp1.worldLocation.x)
		* cosAngle1 - (worldUnrotatedY - cp1.worldLocation.y) *
		sinAngle1);

	cp1.currentPoint.y = cp1.worldLocation.y +
		(int) ((worldUnrotatedX - cp1.worldLocation.x)
		* sinAngle1 + (worldUnrotatedY - cp1.worldLocation.y) *
		cosAngle1);

	// cp1.currentPoint now hold the x/y
	// world coordinates of the first point to test
</pre>
<p>Now, using a pair of vertices at a time, from the asteroid, we translate and rotate both to their final world-space coordinates, ready for the next block of code where we will use the vertex locations calculated in the previous block and this block.</p>
<pre class="brush: java; title: ; notranslate">
/*
	Use two vertices at a time to represent the line we are testing
	We don't test the last vertex because we are testing pairs
	and the last vertex of cp2 is the padded extra vertex.
	It will form part of the last side when we test vertexList[5]
*/

for (int j = 0; j &lt; cp2.vertexListLength - 1; j++) {

	// Now we get the rotated coordinates of
	// BOTH the current 2 points being
	// used to form a side from cp2 (the asteroid)
	// First we need to rotate the model-space
	// coordinate we are testing
	// to its current world position
	// First update the regular un-rotated model space coordinates
	// relative to the current world location (centre of object)

	worldUnrotatedX = cp2.worldLocation.x + cp2.vertexList[j].x;
	worldUnrotatedY = cp2.worldLocation.y + cp2.vertexList[j].y;

	// Now rotate the newly updated point, stored in worldUnrotatedX/y
	// around the centre point of the object (worldLocation)

	cp2.currentPoint.x = cp2.worldLocation.x +
		(int) ((worldUnrotatedX - cp2.worldLocation.x)
		* cosAngle2 - (worldUnrotatedY - cp2.worldLocation.y) *
		sinAngle2);

	cp2.currentPoint.y = cp2.worldLocation.y +
		(int) ((worldUnrotatedX - cp2.worldLocation.x)
		* sinAngle2 + (worldUnrotatedY - cp2.worldLocation.y) *
		cosAngle2);

	// cp2.currentPoint now hold the x/y world coordinates
	// of the first point that
	// will represent a line from the asteroid

	// Now we can do exactly the same for the
	// second vertex and store it in
	// currentPoint2. We will then have a point and a line (two
	// vertices)we can use the
	// crossing number algorithm on.

	worldUnrotatedX = cp2.worldLocation.x
		+ cp2.vertexList[i + 1].x;

	worldUnrotatedY = cp2.worldLocation.y
		+ cp2.vertexList[i + 1].y;

	// Now rotate the newly updated point, stored in worldUnrotatedX/Y
	// around the centre point of the object (worldLocation)
	cp2.currentPoint2.x = cp2.worldLocation.x +
		(int) ((worldUnrotatedX - cp2.worldLocation.x)
		* cosAngle2 - (worldUnrotatedY - cp2.worldLocation.y)
		* sinAngle2);

	cp2.currentPoint2.y = cp2.worldLocation.y +
		(int) ((worldUnrotatedX - cp2.worldLocation.x)
		* sinAngle2 + (worldUnrotatedY - cp2.worldLocation.y)
		* cosAngle2);
</pre>
<p>Here we detect if the current vertex being tested crosses the line formed by the current vertex pair of the asteroid. If it does we increment <pre class="crayon-plain-tag">numCrosses</pre>.</p>
<pre class="brush: java; title: ; notranslate">
// And now we can test the rotated point from cp1 against the
// rotated points which form a side from cp2

if (((cp2.currentPoint.y &gt; cp1.currentPoint.y)
	!= cp2.currentPoint2.y &gt; cp1.currentPoint.y))
	&amp;&amp;(cp1.currentPoint.x &lt;
	(cp2.currentPoint2.x - cp2.currentPoint2.x)
	*(cp1.currentPoint.y - cp2.currentPoint.y)
	/ (cp2.currentPoint2.y 	- cp2.currentPoint.y)
	+ cp2.currentPoint.x)){

	numCrosses++;
} // end if
} // end inner for loop
} // end outer for loop
</pre>
<p>We could have made a separate method to rotate angles as we do this so often. It is not as straightforward as it might seem, however. If we put the rotation code in a method we would either have to put the initial sine and cosine calculations in it which would make it slow or pre-compute them before the method call and the <pre class="crayon-plain-tag">for</pre> loops which is kind of untidy itself.</p>
<p>Also if you consider that we need more than one value for both sine and cosine of an angle, the method needs to &#8216;know&#8217; which to use, which isn&#8217;t rocket science but it starts to get even less compact than we might have initially imagined. So I opted for avoiding the method call altogether, even if the code is a little sprawling.</p>
<p>So if you want to tidy things up, go ahead. I just thought it was worth discussing why I did things this way.</p>
<p>Finally, we use the modulus operator to determine if <pre class="crayon-plain-tag">numCrosses</pre> is odd or even. As discussed, we return <pre class="crayon-plain-tag">true</pre> (collision) for odd and <pre class="crayon-plain-tag">false</pre> (no collision) for even.</p>
<pre class="brush: java; title: ; notranslate">
// So do we have a collision?
if (numCrosses % 2 == 0) {
	// even number of crosses(outside asteroid)
   collided = false;
} else {
	// odd number of crosses(inside asteroid)
   	collided = true;
}

}// end if
</pre>
<p>You can now fly your ship right up to the asteroids and only get hit when it really looks like you should.</p>
<p>You can see the simple Asteroids game I adapted this code from by downloading the <a href="http://gamecodeschool.com/blog/game-code-school-android-app/">GameCodeSchool app</a> from GooglePlay.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/essentials/collision-detection-crossing-number/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collision detection: Neighbour checking</title>
		<link>https://gamecodeschool.com/essentials/collision-detection-neighbour-checking/</link>
		<comments>https://gamecodeschool.com/essentials/collision-detection-neighbour-checking/#comments</comments>
		<pubDate>Mon, 30 May 2016 11:11:41 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Essentials]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=13391</guid>
		<description><![CDATA[This method allows us to only check objects that are in the approximate same area as each other. It can be achieved by checking which neighbourhood of our game a given two objects are in, and then only performing the more CPU intensive collision detection if there is a realistic chance that a collision could [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This method allows us to only check objects that are in the approximate same area as each other. It can be achieved by checking which neighbourhood of our game a given two objects are in, and then only performing the more CPU intensive collision detection if there is a realistic chance that a collision could occur.<br />
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-2 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this tutorial</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to read: 10 minutes</p>
<h4>New Concepts:</h4>
<ol>
<li>Optimizing collision detection with neighbour checking</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/">Rectangle intersect collision detection</a></li>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-radius-overlap/">Radius overlap collision detection</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Projects related to or that demonstrate these concepts</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>None yet <img src="https://gamecodeschool.com/wp-includes/images/smilies/frownie.png" alt=":-(" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>Suppose we have 10 objects that each need to be checked against each other, then we need to perform 10 squared (100) collision checks. If we do neighbour checking first, we can significantly reduce this number. In the very hypothetical situation in the diagram, we would only need to do an absolute maximum of 11 collision checks, instead of 100, for our 10 objects, if we first check to see if objects share the same sector.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2016/05/neighbour-checking-collision-detection-2.png"><img class="aligncenter size-full wp-image-13393" src="http://gamecodeschool.com/wp-content/uploads/2016/05/neighbour-checking-collision-detection-2.png" alt="neighbour-checking-collision-detection-2" width="440" height="441" /></a></p>
<p>Implementing this in code can be as simple as having a sector member variable for each game object, then looping through the list of objects and just checking when they are in the same sector.</p>
<p>Whichever method(s) of collision detection your game uses it is almost always worth doing the neighbor checking of some sort. Sometimes, if your collision detection method is quite intensive, it can be worth performing a less intensive(and probably less precise) collision detection method and when that less intensive method detects a collision, perform more intensive version.</p>
<p>For example in the Crossing number algorithm tutorial we use <a href="http://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/">rectangle intersection</a> as a preliminary check.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/essentials/collision-detection-neighbour-checking/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Collision detection: Radius overlap method</title>
		<link>https://gamecodeschool.com/essentials/collision-detection-radius-overlap-method/</link>
		<comments>https://gamecodeschool.com/essentials/collision-detection-radius-overlap-method/#comments</comments>
		<pubDate>Mon, 30 May 2016 10:48:34 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Essentials]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=13384</guid>
		<description><![CDATA[This method is also checking to see if two shapes intersect with each other, but as the title suggests, it does so using circles. There are advantages and disadvantages compared to other methods. The radius overlap method works well with shapes more circular in nature and less well with elongated shapes as shown in the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>This method is also checking to see if two shapes intersect with each other, but as the title suggests, it does so using circles. There are advantages and disadvantages compared to other methods.<br />
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-3 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this tutorial</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to read: 10 minutes</p>
<h4>New Concepts:</h4>
<ol>
<li>Radius overlap collision detection</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/">Rectangle intersect collision detection</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Projects related to or that demonstrate these concepts</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>None yet <img src="https://gamecodeschool.com/wp-includes/images/smilies/frownie.png" alt=":-(" class="wp-smiley" style="height: 1em; max-height: 1em;" /></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
The radius overlap method works well with shapes more circular in nature and less well with elongated shapes as shown in the image above. From the previous image, it is easy to see how the radius overlapping method is inaccurate for these particular objects and not hard to imagine how for a circular object, like a ball, it would be perfect.</p>
<p>Here is some pseudo code to show how we can implement this method. The code assumes that the <pre class="crayon-plain-tag">ship</pre> and <pre class="crayon-plain-tag">enemy</pre> objects have initialized <pre class="crayon-plain-tag">centerX</pre>, <pre class="crayon-plain-tag">centerY</pre> and <pre class="crayon-plain-tag">radius</pre> member variables. It also assumes that <pre class="crayon-plain-tag">distanceX</pre>, <pre class="crayon-plain-tag">distanceY</pre> have been declared as an appropriate type, possibly float or similar.</p>
<div class="fusion-alert alert notice alert-dismissable alert-warning alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-lg fa-cog"></i></span>Actually the Java, static <pre class="crayon-plain-tag">Math.sqrt</pre> method takes and returns a value of type <pre class="crayon-plain-tag">double</pre>. </div>

<p>The code below doesn&#8217;t mention the types as they will vary depending upon your platform and requirements.</p>
<pre class="brush: java; title: ; notranslate">
// Get the distance of the two objects from
// the edges of the circles on the x axis

distanceX = (ship.centerX + ship.radius) -
	(enemy.centerX + enemy.radius;

// Get the distance of the two objects from
// the edges of the circles on the y axis
distanceY = (ship.centerY + ship.radius) -
	(enemy.centerY + enemy.radius;

// Calculate the distance between the center of each circle
// Math.sqrt is from Java. All modern languages have an equivalent
distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);

// Finally see if the two circles overlap
if (distance &lt; ship.radius + enemy.radius) {
	// bump
}
</pre>
<p>The key to the whole thing is the way we initialize <pre class="crayon-plain-tag">distance</pre>:</p>
<pre class="brush: java; title: ; notranslate">
Math.sqrt(distanceX * distanceX + distanceY * distanceY);
</pre>
<p>If the previous line of code looks a little confusing, it is simply using Pythagoras&#8217; theorem to get the length of the hypotenuse of a triangle which is equal in length to a straight line drawn between the centers of the two circles. In the last line of our solution, we test if distance is greater than the ship.radius + enemy.radius, then we can be certain that we must have a collision. That is because if the center points of two circles are closer than the combined length of their radii, therefore they must be overlapping.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/essentials/collision-detection-radius-overlap-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Collision detection: Rectangle intersect method</title>
		<link>https://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/</link>
		<comments>https://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/#comments</comments>
		<pubDate>Mon, 30 May 2016 09:28:05 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Essentials]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=13373</guid>
		<description><![CDATA[Rectangle intersection detection collision detection is really straightforward. We draw an imaginary rectangle; we can call it a hitbox or bounding rectangle, around the objects we want to test for collision. Then, test to see if they intersect on each and every frame of the game. If they do, we have a collision. Where the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Rectangle intersection detection collision detection is really straightforward. We draw an imaginary rectangle; we can call it a hitbox or bounding rectangle, around the objects we want to test for collision. Then, test to see if they intersect on each and every frame of the game. If they do, we have a collision.</p>
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-4 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this tutorial</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to read: 10 minutes</p>
<h4>New Concepts:</h4>
<ol>
<li>Hitboxes</li>
<li>Rectangle intersection</li>
<li>Android Rect and SFML FloatRect</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li>The game loop</li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Projects related to or that demonstrate these concepts</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/android/coding-a-space-invaders-game/">Coding a Space Invaders game for Android</a></li>
<li><a href="http://gamecodeschool.com/android/coding-a-breakout-game-for-android/">Coding a Breakout(Arkanoid) game for Android</a></li>
<li><a href="http://gamecodeschool.com/sfml/coding-a-simple-pong-game-with-sfml/">Coding a simple Pong game with SFML</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>Where the hitboxes intersect, we have a collision. As we can see from the title image, this is far from perfect. However, in some situations, it is sufficient. To implement this method, all we need to do is test for the intersection using the x and y coordinates of both objects.</p>
<p>This next pseudo code (C++/Java-like) shows the use of a hypothetical <pre class="crayon-plain-tag">getHitBox</pre> method/function.</p>
<pre class="brush: cpp; title: ; notranslate">
if(ship.getHitbox().right &gt; enemy.getHitbox().left
	&amp;&amp; ship.getHitbox().left &lt; enemy.getHitbox().right )
{
	// Ship is intersecting on x axis 

	// But they could be at different heights
	if(ship.getHitbox().top &lt; enemy.getHitbox().bottom  		&amp;&amp; ship.getHitbox().bottom &gt; enemy.getHitbox().top )
	{
		// Ship is intersecting enemy on y axis as well
		// Hit detected - take action
	}
}
</pre>
<p>In the previous code the first <pre class="crayon-plain-tag">if</pre> statement checks whether the right hand side of the ship is at a coordinate greater than the left hand side of the enemy, at the same time as the left hand side of the ship is at a coordinate less than the right hand side of the ship. If both those conditions are true then the two rectangles/hitboxes must be overlapping/intersecting on the horizontal/x axis.</p>
<p>Although the rectangles intersect horizontally it is still possible that they are miles apart vertically. The second <pre class="crayon-plain-tag">if</pre> statement checks whether the top of the ship is at a coordinate less than the bottom of the enemy, at the same time as the bottom of the ship is at a coordinate greater than the top of the enemy.</p>
<div class="fusion-alert alert notice alert-dismissable alert-warning alert-shadow">
  <button type="button" class="close toggle-alert" data-dismiss="alert" aria-hidden="true">&times;</button>
<span class="alert-icon"><i class="fa fa-lg fa-lg fa-cog"></i></span>Note that the vertical detection assumes a coordinate system that increases from top to bottom. This is not always the case.</div>

<p>When both of the <pre class="crayon-plain-tag">if</pre> statements are true, a collision has occurred and we can do whatever is required; destroy the ship, add points, play a sound effect, etc&#8230; All we need to do then is perform these checks from each and every object against each and every object, where we need to detect collisions.</p>
<p>The one thing I haven&#8217;t explained is this mystical <pre class="crayon-plain-tag">getHitbox</pre> method/function. The <pre class="crayon-plain-tag">getHitbox</pre> method probably already exists in your library/API of choice.</p>
<ul>
<li>SFML has a <pre class="crayon-plain-tag">FloatRect</pre> class and you can use code like <pre class="crayon-plain-tag">myFloatRect.x</pre> and <pre class="crayon-plain-tag">myFloatRect.y</pre> etc. In fact, SFML even has an <pre class="crayon-plain-tag">intersects</pre> method which handles everything for you.</li>
<li>The Android API has a <pre class="crayon-plain-tag">Rect</pre> class that works similarly to SFML <pre class="crayon-plain-tag">FloatRect</pre>. The <pre class="crayon-plain-tag">Rect</pre> class has a <pre class="crayon-plain-tag">contains</pre> method that also does all the work for you.</li>
</ul>
<p>Sometimes, however you need to add a bit more functionality to your rectangles/hitboxes so it is worth understanding the simple math that underlies detecting a collision between two rectangles. Then it is worth writing your own code, as above. For example you might want to know whether the collision happened on the left, right, top or bottom. With your own custom <pre class="crayon-plain-tag">hitbox</pre> method/function you could code this functionality into the same class.</p>
<p>If your game objects cannot be represented by rectangles then be sure to take a look at the radius overlap method and the crossing number algorithm. Furthermore, if doing these checks for every object, against every other object, on every frame, sounds like it will badly effect the frame rate then take a look at the Neighbour checking tutorial.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/essentials/collision-detection-rectangle-intersection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rotating graphics in 2d games: Using trigonometric functions part 2</title>
		<link>https://gamecodeschool.com/essentials/rotating-graphics-in-2d-games-using-trigonometric-functions-part-2/</link>
		<comments>https://gamecodeschool.com/essentials/rotating-graphics-in-2d-games-using-trigonometric-functions-part-2/#comments</comments>
		<pubDate>Fri, 12 Jun 2015 09:36:08 +0000</pubDate>
		<dc:creator><![CDATA[John Horton]]></dc:creator>
				<category><![CDATA[Essentials]]></category>

		<guid isPermaLink="false">http://gamecodeschool.com/?p=12175</guid>
		<description><![CDATA[In this second part of the series on trigonometric functions we will use the sine and cosine of an angle to rotate a point around a specific central point. We will then see that by drawing multiple points around the central point and using the same calculation on each we can create the effect of an [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this second part of the series on trigonometric functions we will use the sine and cosine of an angle to rotate a point around a specific central point. We will then see that by drawing multiple points around the central point and using the same calculation on each we can create the effect of an object spinning around.</p>
<div class="fusion-fullwidth fullwidth-box fusion-parallax-none" style="border-color:#e5e4e4;border-bottom-width: 1px;border-top-width: 1px;border-bottom-style: solid;border-top-style: solid;padding-bottom:-120px;padding-left:20px;padding-right:20px;padding-top:20px;background-color:#f8f8f8;background-position:left top;background-repeat:no-repeat;-webkit-background-size:cover;-moz-background-size:cover;-o-background-size:cover;background-size:cover;"><div class="fusion-row"><div class="fusion-content-boxes content-boxes columns fusion-columns-3 fusion-content-boxes-5 content-boxes-icon-with-title row content-left" style="margin-top:0px;margin-bottom:60px;"><div class="fusion-column content-box-column content-box-column-1 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-wrench circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">About this project</h2></div><div class="fusion-clearfix"></div><div class="content-container"> Skill level 1<br />
Time to complete 1 hour</p>
<h4>New Concepts:</h4>
<ol>
<li>Rotating a point about the origin</li>
<li>Object space</li>
<li>World space</li>
</ol>
</div></div></div><div class="fusion-column content-box-column content-box-column-2 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-check circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Recommended preparation tutorials</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/essentials/calculating-heading-in-2d-games-using-trigonometric-functions-part-1/">Calculating heading in 2d games: Using trigonometric functions part 1</a></li>
</ul>
</div></div></div><div class="fusion-column content-box-column content-box-column-3 col-lg-4 col-md-4 col-sm-4"><div class="col content-wrapper"><div class="heading heading-with-icon icon-left"><div class="icon"><i style="height:42px;width:42px;line-height:42px;font-size:21px;" class="fa fontawesome-icon fa-road circle-yes"></i></div><h2 class="content-box-heading" style="font-size: 18px;line-height:20px;">Projects that demonstrate these concepts</h2></div><div class="fusion-clearfix"></div><div class="content-container">
<ul>
<li><a href="http://gamecodeschool.com/android/2d-rotation-and-heading-demo/">Android 2d rotation and heading demo</a></li>
</ul>
</div></div></div><div class="fusion-clearfix"></div><div class="fusion-clearfix"></div></div></div></div><div class="fusion-sep-clear"></div><div class="fusion-separator fusion-full-width-sep sep-none" style="border-color:#e0dede;margin-left: auto;margin-right: auto;margin-top:20px;"></div>
<p>Rotating a point around a central point is actually really simple. Here is the algorithm.</p>
<p>rotated point x = original x * cosine (angle in radians to change by) &#8211; original y  * sine (angle in radians to change by)<br />
rotated point y = original x * sine (angle in radians to change by) + original y * cosine (angle in radians to change by)</p>
<p>Notice the subtle but important differences in finding the rotated y coordinate compared to finding the rotated x coordinate.</p>
<p>However, implementing this algorithm in a game takes a bit more discussion. First, let&#8217;s look at some really simple angles and coordinates where we don&#8217;t really need a fancy algorithm, to prove that this works.</p>
<p>Assume that we have a point at -10, -10 and we rotate it 180 degrees around the point 0,0. We don&#8217;t need the algorithm to know that the rotated point will end up at 10,10 as shown in the next diagram.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/06/rotating_a_point_around_the_origin.png"><img class="aligncenter wp-image-12179 size-full" src="http://gamecodeschool.com/wp-content/uploads/2015/06/rotating_a_point_around_the_origin.png" alt="rotating_a_point_around_the_origin" width="600" height="570" /></a></p>
<p>&nbsp;</p>
<h2>Doing the math</h2>
<p>Let&#8217;s break up the algorithm and run the numbers through it a step at a time. If all is well we should come up with the rotated coordinates 10,10.</p>
<p>Starting with finding the rotated  x. Here is a reminder of how we find x.</p>
<p>rotated point x = original x * cosine (angle in radians to change by) &#8211; original y  * sine (angle in radians to change by)</p>
<h3>X Step 1: original x * cosine (angle to change by)</h3>
<p>-10 * cosine of <a href="http://gamecodeschool.com/essentials/calculating-heading-in-2d-games-using-trigonometric-functions-part-1/">radian equivalent</a> of 180 =</p>
<p>-10 * cosine of pi / 180 * 180 =</p>
<p>-10 * cosine of 3.1415926535897932384626433832795 =</p>
<p>-10 * -1 =</p>
<p>= <span style="text-decoration: underline;">10</span></p>
<h3>X Step 2: original y  * sine (angle in radians to change by)</h3>
<p>-10 * sine of radian equivalent of 180 =</p>
<p>-10 * sine of pi / 180 * 180 =</p>
<p>-10 * sine of 3.1415926535897932384626433832795 =</p>
<p>&#8211; 10 * 0 =</p>
<p>= <span style="text-decoration: underline;">0</span></p>
<h3>X Step 3: part 1 &#8211; part 2</h3>
<p>10 &#8211; 0 =</p>
<p><span style="text-decoration: underline;">10</span></p>
<p>So x = 10. Yay!</p>
<p>Now for y. Here is a reminder of how we find y.<br />
rotated point y = original x * sine (angle in radians to change by) + original y * cosine (angle in radians to change by)</p>
<h3>Y Part 1: original x * sine (angle in radians to change by)</h3>
<p>-10 * sine of radian equivalent of 180 =</p>
<p>-10 * sine of pi / 180 * 180 =</p>
<p>-10 * sine of 3.1415926535897932384626433832795 =</p>
<p>&#8211; 10 * 0 =</p>
<p>= <span style="text-decoration: underline;">0</span></p>
<h3>Y Part 2: original y * cosine (angle in radians to change by)</h3>
<p>-10 * cosine of <a href="http://gamecodeschool.com/essentials/calculating-heading-in-2d-games-using-trigonometric-functions-part-1/">radian equivalent</a> of 180 =</p>
<p>-10 * cosine of pi / 180 * 180 =</p>
<p>-10 * cosine of 3.1415926535897932384626433832795 =</p>
<p>-10 * -1 =</p>
<p>= <span style="text-decoration: underline;">10</span></p>
<h3>Y Part 3: part 1 + part 2</h3>
<p>0 + 10 =</p>
<p><span style="text-decoration: underline;">10</span></p>
<p>So y = 10. Yay!</p>
<p>So as we can see the results are as expected. But we need to do more to put this into action in a 2d game.</p>
<h2>Object space and world space</h2>
<p>The problem is that this algorithm will only work when the centre of the rotation is zero. This is known as the <strong>origin</strong>. This is why we used the example that we did. It is not to say that there aren&#8217;t some cool uses for doing rotations around points other than 0,0 but that is for another article.</p>
<p>All of a sudden our algorithm might seem a little bit useless. However, it is quite simple to accommodate this requirement. We just need to treat each of the objects in our game as having there own coordinate system known as <strong>object space</strong> yet still existing in the larger game world known as <strong>world space</strong>.</p>
<p><a href="http://gamecodeschool.com/wp-content/uploads/2015/06/world_and_object_space.png"><br />
</a><a href="http://gamecodeschool.com/wp-content/uploads/2015/06/world_and_object_space.png"><img class="aligncenter size-full wp-image-12193" src="http://gamecodeschool.com/wp-content/uploads/2015/06/world_and_object_space.png" alt="world_and_object_space" width="600" height="346" /></a></p>
<p>The simple trick to managing these two different coordinate systems is to track a centre point of the object in world space coordinates as well as the three points that make up the actual vertices of the object.</p>
<p>So let&#8217;s say that in the previous image the centre point of the object is in the exact centre of the screen and the resolution of the device is 1920 x 1080. The centre of the object has the coordinates 960, 540.  Also, We can therefore, draw lines between the three vertices as follows:</p>
<p><strong>point a</strong> at centre x, centre y + 150 = <span style="text-decoration: underline;">960, 690</span></p>
<p><strong>point b</strong> at centre x &#8211; 75, centre y &#8211; 150 = <span style="text-decoration: underline;">885, 390</span></p>
<p><strong>point c</strong> at centre x + 75, centre y &#8211; 150 = <span style="text-decoration: underline;">1035, 390</span></p>
<p>Simply join up the dots with three lines and we have our cool triangle spaceship. The problem is that if we try and rotate any of those points, perhaps <strong>a</strong> (960, 690) we will get results that are totally unusable for rotating our spaceship. In fact, the point would disappear entirely from the screen. Try it with the algorithm we have recently stepped through if you like. However if we simply subtract the centre point from each of the others we will then have a zero based, object space coordinate range identical to the coordinates above and our rotation algorithm will work just fine.</p>
<p>So the solution is as follows. To rotate the spaceship each frame:</p>
<ol>
<li>subtract centre x from point a x</li>
<li>subtract centre y from point a y</li>
<li>rotate point a</li>
<li>add centre x to point a x</li>
<li>add centre y to point a y</li>
<li>repeat from step 1 for points b and c as well</li>
<li>draw the spaceship at the new coordinates</li>
</ol>
<p>Let&#8217;s go ahead and <a href="http://gamecodeschool.com/android/2d-rotation-and-heading-demo/">try this out for real</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://gamecodeschool.com/essentials/rotating-graphics-in-2d-games-using-trigonometric-functions-part-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
