<?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>RudiYardley.com &#187; Actionscript</title>
	<atom:link href="http://blog.rudiyardley.com/category/actionscript/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.rudiyardley.com</link>
	<description>Technical tidbits on Flash, Flex, Application Development, MODx, Silverstripe and Freelancing</description>
	<lastBuildDate>Tue, 31 Jan 2012 04:31:03 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Organising your Data Access Layer in an AIR Flex Application</title>
		<link>http://blog.rudiyardley.com/2011/03/organising-your-data-access-layer-in-a-air-flex-application/</link>
		<comments>http://blog.rudiyardley.com/2011/03/organising-your-data-access-layer-in-a-air-flex-application/#comments</comments>
		<pubDate>Sat, 19 Mar 2011 04:40:24 +0000</pubDate>
		<dc:creator>rudi</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://blog.rudestar.net/?p=481</guid>
		<description><![CDATA[With the advent of AIR technologies, the Flex developer now has the ability to save data to the bundled SQLite relational database, which is pretty much a requirement for any desktop application these days. Many Flex developers like myself that come from a Flash or front end background, may not necessarily be familiar with the [...]]]></description>
			<content:encoded><![CDATA[<p>With the advent of AIR technologies, the Flex developer now has the ability to save data to the bundled SQLite relational database, which is pretty much a requirement for any desktop application these days. Many Flex developers like myself that come from a Flash or front end background, may not necessarily be familiar with the design patterns involved in accessing and mapping data to and from a relational database. The examples that come in the AIR documentation only deliver the basic usecase to demonstrate language features and don&#8217;t always apply the necessary level of abstraction to come up with solutions that are elegant, hide complexity sufficiently and allow for great scalability.</p>
<p>For areas of common standard functionality, where the project maintenance is likely to change hands, I usually recommend using a well built and well documented framework when building Rich Applications but know how important it is to understand the underlying architecture and design patterns a framework uses so as to have a better understanding of any given system. There are a few ORM (Object Relational Mapping) solutions for AIR emerging on the market now such as <a href="http://flexorm.riaforge.org/">FlexORM</a> that have caught my eye, many of them using annotations to map classes to database records but what sort of complexity are those ORM solutions managing?</p>
<p>I have recently been reading Martin Fowler&#8217;s excellent book <a href="http://www.amazon.com/Patterns-Enterprise-Application-Architecture-Martin/dp/0321127420">Patterns of Enterprise Application Architecture</a> and saw several things I could bring to my own application development toolkit. So in order to better understand the patterns suggested by Fowler, I decided to test the waters and build a basic custom ORM system that I could use on small bespoke projects such as my own projects, where I would be in control of maintenance. Fowler mentions several patterns including Active Record, Data Mapper, Unit of Work, Lazy Load plus many others devoted to the specifics of relational mapping.</p>
<p>Upon researching the subject, it appears that fundamental to the architecture or your Data Access Layer is the decision of whether to follow <a href="http://en.wikipedia.org/wiki/Active_Record">Active Record</a> or <a href="http://martinfowler.com/eaaCatalog/dataMapper.html">Data Mapper</a>. Now generally, I am not a huge fan of Active Record for a couple of reasons; firstly, from my experiences with Silverlight and Cake it tends to lead to an oversimplification of the data structure, which often means the data of your application does not represent the problem domain accurately. Since the key to developing a quality app is getting the data structure correct, this will likely affect the optimizability and maintainability of your application in the long run. Secondly Active Record breaks the Principle of Single Responsibility within Object Oriented Programming which brings class bloat as model classes cope with both the Domain based business rules as well as the responsibilities of mapping to the database. So since using Active Record does not feel to me like a best practice, we are left with using Data Mapper to structure the data access layer.</p>
<p>So with a Data Mapper approach chosen, from then on in what are the patterns that are the most important to success on a basic level? How should you structure simple projects where you want an organised data layer but don&#8217;t know where to start? Let&#8217;s break it down into components:</p>
<h2>Controlling what needs to be done: Unit Of Work</h2>
<p>The Unit of Work Pattern takes a domain object and flags that domain object for an action by the appropriate Data Mapper without actually doing the action until it&#8217;s commit() method is called. This way database calls may be managed using bulk transactions limiting individual transactions. UnitOfWork&#8217;s main two functional modes are that of flagging objects that are out out of sync with the DB and committing the queued changes to the database. This has the effect of making fewer database&nbsp;transactions as transactions can be postponed till all the relevant fields are changed and the commit function is run. When you can imagine that the alternative would be to run a transaction every single time a field is changed you can see quickly how this pattern can help speed things up. The Unit of Work has methods for managing new,dirty and deleted objects as you can see here:</p>
<h6>Fig. 1.1 Unit if Work UML</h6>
<p><a href="http://blog.rudestar.net/wp-content/uploads//UnitOfWork.jpg"><img class="alignnone size-full wp-image-493" title="UnitOfWork" src="http://blog.rudestar.net/wp-content/uploads//UnitOfWork.jpg" alt="UnitOfWork" width="225" height="140" /></a></p>
<h6>Fig. 1.2 Unit of Work Actionscript Class</h6>
<p><!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li></li><li>package com.rudiyardley.dbapp.db</li><li><span class="br0">&#123;</span></li><li>	import com.rudiyardley.dbapp.model.DomainObject;</li><li>	import com.rudiyardley.dbapp.model.Student;</li><li>&nbsp;</li><li>	public class UnitOfWork</li><li>	<span class="br0">&#123;</span></li><li>&nbsp;</li><li>		private var newObjects:Array;</li><li>		private var dirtyObjects:Array;</li><li>		private var deletedObjects:Array;</li><li>&nbsp;</li><li>		public var identityMap:IIdentityMap;</li><li>&nbsp;</li><li>		public function UnitOfWork<span class="br0">&#40;</span>s:ForceSingle<span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			newObjects = new Array<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			dirtyObjects = new Array<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			deletedObjects = new Array<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		public function registerDirty<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			dirtyObjects.push<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		public function registerClean<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			dirtyObjects.splice<span class="br0">&#40;</span>dirtyObjects.indexOf<span class="br0">&#40;</span>object<span class="br0">&#41;</span>,1<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		public function registerDeleted<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			deletedObjects.push<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	Object will be placed in the DB with an insert statement</li><li>		public function registerNew<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			newObjects.push<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>			registerClean<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		public function commit<span class="br0">&#40;</span><span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			var mapper:IDataMapper;</li><li>			var object:DomainObject;</li><li>&nbsp;</li><li>			while<span class="br0">&#40;</span>newObjects.length&gt;0<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				object = newObjects.shift<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>				mapper = DataSession.current.getMapper<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>				mapper.create<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>			<span class="br0">&#125;</span></li><li>&nbsp;</li><li>			while<span class="br0">&#40;</span>dirtyObjects.length&gt;0<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				object = dirtyObjects.shift<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>				mapper = DataSession.current.getMapper<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>				mapper.update<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>			<span class="br0">&#125;</span></li><li>&nbsp;</li><li>&nbsp;</li><li>			while<span class="br0">&#40;</span>deletedObjects.length&gt;0<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				object = deletedObjects.shift<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>				mapper = DataSession.current.getMapper<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;</li><li>				mapper.deleteItem<span class="br0">&#40;</span>object<span class="br0">&#41;</span>;				</li><li>			<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		<span class="br0">&#125;</span></li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<h2>Reading to and From the Database: DataMapper</h2>
<p>How do you interface with the DB so that your persistence logic is separate from your application yet not acting as a transactional mess? A data mapper is responsible for translating between domain objects and the database. Usually you will have one class per domain object. You put in an object in the appropriate accessor method and the DataMapper creates,reads,updates or deletes it. Note the data mapper is usually object specific and every persistent DomainObject should have a corresponding DataMapper. DataMappers should live within the DataSession and can also maintain identity maps there for caching whenever reading from the database.</p>
<h6>Fig. 1.3 A typical abstract DataMapper:</h6>
<p><a href="http://blog.rudestar.net/wp-content/uploads//DataMapper1.jpg"><img class="alignnone size-full wp-image-498" title="DataMapper" src="http://blog.rudestar.net/wp-content/uploads//DataMapper1.jpg" alt="DataMapper" width="225" height="132" /></a></p>
<p>The DataMapper above represents the main things you will tend to need from a data mapper. A specific mapper may contain more methods depending on what type of searches it requires. A Domain Object&#8217;s corresponding mapper should contain the logic for building all the SQL responsible for it&#8217;s persistence in the database. An easy way to prepare and select appropriate mappers is to have some kind of Factory Method on the DataSession object that accepts a Class reference and spits out a mapper. ie.<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li></li><li>DataSession.current.getMapper<span class="br0">&#40;</span>GalleryImage<span class="br0">&#41;</span>;	// Would return a GalleryImage mapper.</li><li></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<h6>Fig. 1.4 Source of a typical DataMapper</h6>
<p><!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li></li><li>package com.rudiyardley.dbapp.db</li><li><span class="br0">&#123;</span></li><li>	import com.rudiyardley.dbapp.model.DomainObject;</li><li>	import com.rudiyardley.dbapp.model.Student;</li><li>&nbsp;</li><li>	import flash.data.SQLConnection;</li><li>	import flash.data.SQLResult;</li><li>	import flash.data.SQLStatement;</li><li>&nbsp;</li><li>	import mx.collections.ArrayCollection;</li><li>&nbsp;</li><li>	public class StudentMapper implements IDataMapper</li><li>	<span class="br0">&#123;</span></li><li>		private var stmtInit:SQLStatement;</li><li>		private var stmtCreate:SQLStatement;</li><li>		private var stmtUpdate:SQLStatement;</li><li>		private var stmtDeleteItem:SQLStatement;</li><li>		private var stmtReadAll:SQLStatement;</li><li>		private var stmtReadById:SQLStatement;</li><li>&nbsp;</li><li>		private var map:IIdentityMap;</li><li>&nbsp;</li><li>		public function StudentMapper<span class="br0">&#40;</span>conn:SQLConnection,map:IIdentityMap<span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			this.map = map;</li><li>&nbsp;</li><li>			//	Initialize the other queries</li><li>			stmtInit = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			stmtCreate = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			stmtUpdate = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			stmtDeleteItem = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			stmtReadAll = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			stmtReadById = new SQLStatement<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>			//	apply the connection</li><li>			stmtInit.sqlConnection = conn;</li><li>			stmtCreate.sqlConnection = conn;</li><li>			stmtUpdate.sqlConnection = conn;</li><li>			stmtDeleteItem.sqlConnection = conn;</li><li>			stmtReadAll.sqlConnection = conn;</li><li>			stmtReadById.sqlConnection = conn;</li><li>&nbsp;</li><li>			initDB<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	CREATE TABLE</li><li>		private function initDB<span class="br0">&#40;</span><span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			stmtInit.text = &quot;CREATE TABLE IF NOT EXISTS students <span class="br0">&#40;</span> id TEXT PRIMARY KEY, name TEXT <span class="br0">&#41;</span>; &quot;;</li><li>			stmtInit.execute<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	READ ALL</li><li>		public function readAll<span class="br0">&#40;</span><span class="br0">&#41;</span>:ArrayCollection</li><li>		<span class="br0">&#123;</span></li><li>			var result:SQLResult;</li><li>			var items:ArrayCollection;</li><li>			var i:int;</li><li>			var dataObject:Object;</li><li>			var currentStudent:Student;</li><li>&nbsp;</li><li>			//	Prepare statement</li><li>			stmtReadAll.text = &quot;SELECT * FROM students;&quot;;</li><li>			stmtReadAll.execute<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>			//	Get results and iterate over result</li><li>			result = stmtReadAll.getResult<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			items = new ArrayCollection<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			if<span class="br0">&#40;</span>result.data != null<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				for<span class="br0">&#40;</span>i=<span style="">0</span>;i&lt;result.data.length;i++<span class="br0">&#41;</span></li><li>				<span class="br0">&#123;</span></li><li>					dataObject = result.data<span class="br0">&#91;</span>i<span class="br0">&#93;</span>;</li><li>					currentStudent = createCleanDomainObjectFromDataObject<span class="br0">&#40;</span>dataObject<span class="br0">&#41;</span> as Student;</li><li>					DataSession.current.registerObject<span class="br0">&#40;</span>currentStudent<span class="br0">&#41;</span>;</li><li>					items.addItem<span class="br0">&#40;</span>currentStudent<span class="br0">&#41;</span>;</li><li>				<span class="br0">&#125;</span></li><li>			<span class="br0">&#125;</span></li><li>			return items;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	READ BY ID</li><li>		public function readById<span class="br0">&#40;</span>id:String<span class="br0">&#41;</span>:DomainObject</li><li>		<span class="br0">&#123;</span></li><li>			var result:SQLResult;</li><li>			var studentToReturn:Student;</li><li>			var dataObject:Object;</li><li>&nbsp;</li><li>			studentToReturn = map.getObjectByTypeId<span class="br0">&#40;</span>Student,id<span class="br0">&#41;</span> as Student;</li><li>&nbsp;</li><li>			if<span class="br0">&#40;</span>studentToReturn != null<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				return studentToReturn;</li><li>			<span class="br0">&#125;</span></li><li>&nbsp;</li><li>			stmtReadById.text = &quot;SELECT * FROM students WHERE id=:id;&quot;;</li><li>			stmtReadById.parameters<span class="br0">&#91;</span>&quot;:id&quot;<span class="br0">&#93;</span> = id;</li><li>			stmtReadById.execute<span class="br0">&#40;</span>1<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>&nbsp;</li><li>			result = stmtReadById.getResult<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			if<span class="br0">&#40;</span>result.data == null<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				return null;</li><li>			<span class="br0">&#125;</span></li><li>			stmtReadById.cancel<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			dataObject = result.data<span class="br0">&#91;</span>0<span class="br0">&#93;</span>;</li><li>			studentToReturn = createCleanDomainObjectFromDataObject<span class="br0">&#40;</span>result.data<span class="br0">&#91;</span>0<span class="br0">&#93;</span><span class="br0">&#41;</span> as Student;</li><li>			DataSession.current.registerObject<span class="br0">&#40;</span>studentToReturn<span class="br0">&#41;</span>;</li><li>			return studentToReturn;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	CREATE</li><li>		public function create<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			if<span class="br0">&#40;</span>readById<span class="br0">&#40;</span>object.id<span class="br0">&#41;</span>==null<span class="br0">&#41;</span></li><li>			<span class="br0">&#123;</span></li><li>				stmtCreate.text = &quot;INSERT INTO students <span class="br0">&#40;</span>id,name<span class="br0">&#41;</span> VALUES <span class="br0">&#40;</span>:id,:name<span class="br0">&#41;</span>;&quot;;</li><li>				stmtCreate.parameters<span class="br0">&#91;</span>&quot;:id&quot;<span class="br0">&#93;</span> = Student<span class="br0">&#40;</span>object<span class="br0">&#41;</span>.id;</li><li>				stmtCreate.parameters<span class="br0">&#91;</span>&quot;:name&quot;<span class="br0">&#93;</span> = Student<span class="br0">&#40;</span>object<span class="br0">&#41;</span>.name;</li><li>				stmtCreate.execute<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			<span class="br0">&#125;</span></li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	UPDATE</li><li>		public function update<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>			stmtUpdate.text = &quot;UPDATE students SET name=:name WHERE id=:id; &quot;;</li><li>			stmtUpdate.parameters<span class="br0">&#91;</span>&quot;:id&quot;<span class="br0">&#93;</span> = Student<span class="br0">&#40;</span>object<span class="br0">&#41;</span>.id;</li><li>			stmtUpdate.parameters<span class="br0">&#91;</span>&quot;:name&quot;<span class="br0">&#93;</span> = Student<span class="br0">&#40;</span>object<span class="br0">&#41;</span>.name;</li><li>			stmtUpdate.execute<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span>;</li><li>&nbsp;</li><li>		//	DELETE</li><li>		public function deleteItem<span class="br0">&#40;</span>object:DomainObject<span class="br0">&#41;</span>:void</li><li>		<span class="br0">&#123;</span></li><li>&nbsp;</li><li>			stmtDeleteItem.text = &quot;DELETE FROM students WHERE id = :id ; &quot;;</li><li>			stmtDeleteItem.parameters<span class="br0">&#91;</span>&quot;:id&quot;<span class="br0">&#93;</span> = Student<span class="br0">&#40;</span>object<span class="br0">&#41;</span>.id;</li><li>			stmtDeleteItem.execute<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span>;</li><li>&nbsp;</li><li>		//	Utility function creates a clean domain object</li><li>		private function createCleanDomainObjectFromDataObject<span class="br0">&#40;</span>dataObject:Object<span class="br0">&#41;</span>:DomainObject</li><li>		<span class="br0">&#123;</span></li><li>			var student:Student = new Student<span class="br0">&#40;</span>dataObject.id,dataObject.name<span class="br0">&#41;</span>;</li><li>			student.markClean<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>			return student;</li><li>		<span class="br0">&#125;</span></li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li>&nbsp;</li><li></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<h3>Handling ID&#8217;s using GUIDS</h3>
<p>One of the issues I found in working with the fowler patterns was that when doing basic bulk writes or reads Actionscript APIs don&#8217;t allow access to the most recent row ID of a record until the entire transaction has been completed. A strategy I found to solve this problem was to create ID&#8217;s external to the database. One way to do this was to incrementally update a purpose created field the database every time a record was added to keep track of the currently written id. A simpler method was to use a GUID generator to accomplish the same ends.<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li></li><li>var s:Student = new Student<span class="br0">&#40;</span>IdGenerator.instance.getId<span class="br0">&#40;</span><span class="br0">&#41;</span>,name<span class="br0">&#41;</span>;</li><li></li></ol></div></pre><!--END_DEVFMTCODE--><br />
For your information the GUID creator I use comes from <a href="http://www.rgbeffects.com/blog/actionscript/actionscript-3-guid-%E2%80%93-generating-unique-ids-for-users-in-as3/">RGBlog</a>.</p>
<h3>Keeping track of identities: IdentityMap</h3>
<p>When you have objects that represent objects within the database it is important to keep track of all the objects out there in memory. To this end we can use a registry associated with the data session.</p>
<h3>Downloadable Example</h3>
<p>I have put together an example of a data access layer within the context of a simple and rather hastily constructed application that can act as an example of the patterns at work here. The application manages a many to many relationship between Teachers and Students. To use the application you can create Teachers or Students and the application adds them to the lists. Then select both a teacher and student together and you can create a relationship.</p>
<p>You can download the source code <a href="/wp-content/uploads/DataApplication.zip?phpMyAdmin=rutTBiA3QroFIysWggFI8Rzcq40" target="_blank">here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rudiyardley.com/2011/03/organising-your-data-access-layer-in-a-air-flex-application/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How to calculate the intersection of two circles mathematically in Actionscript.</title>
		<link>http://blog.rudiyardley.com/2010/01/how-to-calculate-the-intersection-of-two-circles-mathematically-in-actionscript/</link>
		<comments>http://blog.rudiyardley.com/2010/01/how-to-calculate-the-intersection-of-two-circles-mathematically-in-actionscript/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 11:20:58 +0000</pubDate>
		<dc:creator>rudi</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Scripted Animation]]></category>

		<guid isPermaLink="false">http://blog.rudestar.net/?p=279</guid>
		<description><![CDATA[A client of mine wanted to create an interactive teacher animation that pointed to a point on a chart that could be calculated as the result of a user quiz. They were stuck though as creating a realistic elbow movement that points to the desired point from a programmatic perspective is actually harder than it [...]]]></description>
			<content:encoded><![CDATA[<p>A client of mine wanted to create an interactive teacher animation that pointed to a point on a chart that could be calculated as the result of a user quiz. They were stuck though as creating a realistic elbow movement that points to the desired point from a programmatic perspective is actually harder than it seems as most teachers arms tend to have elbows. The solution took some time to come up with although simple enough in the end after a bit of geometric research. The first step to creating the animation was to calculate mathematically the intersections of two circles.</p>
<p>Finding the intersection of two circles appears complicated although in actual fact it is just a matter of unraveling Pythagoras&#8217; Theorem a few times. Pythagoras&#8217; Theorem states that the sum of square of the both straight sides of any right angled triangle is equal to the square of the diagonal.</p>
<p>ie. <em>a<sup>2</sup>=b<sup>2</sup>+c<sup>2</sup></em></p>
<p>Here is how you use it to find the intersection points of a circle with Actionscript:</p>
<p>1) Start by creating a couple of draggable circles and some hidden dots that will be used to indicate where the intersections are:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title="'actionscript'"><div class="devcodeoverflow"><ol><li>package</li><li>{</li><li>	import flash.display.Sprite;</li><li>	import flash.geom.Point;</li><li>	import flash.events.Event;</li><li>	import flash.events.MouseEvent;</li><li></li><li>	public class FindIntersection extends Sprite</li><li>	{</li><li>		public var circle1Radius:Number = 40;</li><li>		public var circle2Radius:Number = 70;</li><li>		public var circle1:Sprite = drawCircle(circle1Radius);</li><li>		public var circle2:Sprite = drawCircle(circle2Radius);</li><li>		public var dot1:Sprite = drawDot();</li><li>		public var dot2:Sprite = drawDot();</li><li></li><li>		function FindIntersection()</li><li>		{</li><li>			var origin:Point = new Point(stage.stageWidth/2, stage.stageHeight/2);</li><li>			circle1Radius = 40;</li><li>			circle2Radius = 70;</li><li>			circle1 = drawCircle(circle1Radius);</li><li>			circle2 = drawCircle(circle2Radius);</li><li>			dot1 = drawDot();</li><li>			dot2 = drawDot();</li><li>			circle1.x = origin.x - 10;</li><li>			circle1.y = origin.y;</li><li>			circle2.x = origin.x + 10;</li><li>			circle2.y = origin.y;</li><li>			addChild(circle1);</li><li>			addChild(circle2);</li><li>			addChild(dot1);</li><li>			addChild(dot2);</li><li>		}</li><li></li><li>		function drawCircle(rad:Number):Sprite</li><li>		{</li><li>			var c:Sprite = new Sprite();</li><li>			c.graphics.lineStyle(1,0x000000);</li><li>			c.graphics.beginFill(0xBBBBBB,.1);</li><li>			c.graphics.drawCircle(0,0,rad);</li><li>			c.graphics.endFill();</li><li>			c.graphics.moveTo(-5,0);</li><li>			c.graphics.lineTo(5,0);</li><li>			c.graphics.moveTo(0,-5);</li><li>			c.graphics.lineTo(0,5);</li><li>			c.addEventListener(MouseEvent.MOUSE_DOWN, onDown);</li><li>			c.addEventListener(MouseEvent.MOUSE_UP, onUp);</li><li>			return c;</li><li>		}</li><li></li><li>		function drawDot()</li><li>		{</li><li>			var d:Sprite = new Sprite();</li><li>			d.graphics.beginFill(0xFF0000);</li><li>			d.graphics.drawCircle(0,0,2);</li><li>			d.graphics.endFill();</li><li>			d.visible = false;</li><li>			return d;</li><li>		}</li><li></li><li>		function onDown(e:Event):void</li><li>		{</li><li>			var circle:Sprite = e.target&nbsp;&nbsp;as&nbsp;&nbsp;Sprite;</li><li>			circle.startDrag();</li><li>		}</li><li></li><li>		function onUp(e:Event):void</li><li>		{</li><li>			var circle:Sprite = e.target&nbsp;&nbsp;as&nbsp;&nbsp;Sprite;</li><li>			circle.stopDrag();</li><li>		}</li><li></li><li>	}</li><li>}</li></ol></div></pre><!--END_DEVFMTCODE--><br />
2) Next add an enterframe handler that checks for a collision by calculating the distance between the two circles. If the distance is greater than the sum of the radiae of both circles there is no intersection. Also if the distance is less than the absolute difference between the radiae then there is no solution as one circle is contained within the other.<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>function enterFrameHandler<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li><span class="br0">&#123;</span></li><li>	// Set up variables</li><li>	var r0:Number = circle1Radius;</li><li>	var r1:Number = circle2Radius;</li><li>&nbsp;</li><li>	// Point x and y coords</li><li>	var p0x:Number = circle1.x;</li><li>	var p0y:Number = circle1.y;</li><li>	var p1x:Number = circle2.x;</li><li>	var p1y:Number = circle2.y;</li><li>&nbsp;</li><li>	//First calculate the distance d between the center of the circles. d = ||P1 - P0||.</li><li>	var dx:Number = p0x - p1x;</li><li>	var dy:Number = p0y - p1y;</li><li>	var d:Number = Math.sqrt<span class="br0">&#40;</span>dx*dx + dy*dy<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>	//If d &gt; r0 + r1 then there are no solutions, the circles are separate.</li><li>	//If d &lt; |r0 - r1| then there are no solutions because one circle is contained within the other. 	if <span class="br0">&#40;</span><span class="br0">&#40;</span>d &gt; r0 + r1<span class="br0">&#41;</span> ||</li><li>	<span class="br0">&#40;</span>d &lt; Math.abs<span class="br0">&#40;</span>r0 - r1<span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		dot1.visible = false;</li><li>		dot2.visible = false;</li><li>		return;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />
<img class="alignnone size-full wp-image-303" title="CircleIntersection1" src="http://blog.rudestar.net/wp-content/uploads//CircleIntersection1.jpg" alt="CircleIntersection1" width="400" height="300" /></p>
<p>The way we calculate distance is by using Pythagoras&#8217; formula by determining distance as a hypotenuse of a right angled triangle calculated as the square root of the square of the x-difference plus the square of the y-difference. ie.</p>
<p><em>d=√( dx<sup>2</sup>+dy<sup>2</sup> )</em></p>
<p>3) Now comes something slightly trickier. Consider the following diagram:</p>
<p><img class="alignnone size-full wp-image-293" title="CircleIntersection" src="http://blog.rudestar.net/wp-content/uploads//CircleIntersection.jpg" alt="CircleIntersection" width="400" height="300" /></p>
<p>Again using Pythagoras we can say that:</p>
<p><em>a<sup>2</sup>+ h<sup>2</sup>= r<sub>0</sub><sup>2</sup></em> is true for the red triangle and <em>b<sup>2</sup>+ h<sup>2</sup>= r<sub>1</sub><sup>2</sup></em> is true for the green triangle.</p>
<p>Now knowing that <em>d = a + b</em> we can then use a bit of algebra to solve for <em>a</em> in terms of<em> r<sub>0</sub></em>, <em>r<sub>1</sub></em> and <em>d</em> (I can show the working here if you want just leave a comment or send me a message):</p>
<p><em>a = (r<sub>0</sub><sup>2</sup> &#8211; r<sub>1</sub><sup>2</sup> + d<sup>2</sup> ) / (2 d)</em></p>
<p>Which we can write in actionscript as:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>var a:Number = <span class="br0">&#40;</span> r0*r0 - r1*r1 + d*d <span class="br0">&#41;</span> / <span class="br0">&#40;</span>2*d<span class="br0">&#41;</span>;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
Have a look at the following diagram:</p>
<p><img class="alignnone size-full wp-image-316" title="CircleIntersection2" src="http://blog.rudestar.net/wp-content/uploads//CircleIntersection2.jpg" alt="CircleIntersection2" width="400" height="300" /></p>
<p>Now since P<sub>2</sub> is along the line distance <em>d</em> and the <em>x</em> and <em>y</em> coordinates are relative to <em>a/d</em> therefore:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>var p2x:Number = p0x + a * <span class="br0">&#40;</span> p1x - p0x <span class="br0">&#41;</span> / d;</li><li>var p2y:Number = p0y + a * <span class="br0">&#40;</span> p1y - p0y <span class="br0">&#41;</span> / d;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
Since we know that <em>r<sub>0</sub><sup>2</sup> = h<sup>2</sup>+ a<sup>2</sup></em> and now that we have the value of <em>a</em> we can get <em>h</em> using pythagoras yet again:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>var h:Number = Math.sqrt<span class="br0">&#40;</span>r0*r0 - a*a<span class="br0">&#41;</span>;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
Now all that is left to do is project the positive <em>h</em> point and the negative <em>h</em> point:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>	var d1x:Number = p2x + h * <span class="br0">&#40;</span> p1y - p0y <span class="br0">&#41;</span> / d;</li><li>	var d1y:Number = p2y - h * <span class="br0">&#40;</span> p1x - p0x <span class="br0">&#41;</span> / d;</li><li>	var d2x:Number = p2x - h * <span class="br0">&#40;</span> p1y - p0y <span class="br0">&#41;</span> / d;</li><li>	var d2y:Number = p2y + h * <span class="br0">&#40;</span> p1x - p0x <span class="br0">&#41;</span> / d;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
Now we have the points of intersection, our file should look something like this:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="530" height="398" align="left">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/FindIntersection1.swf" />
      <param name="align" value="left" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/FindIntersection1.swf" width="530" height="398" align="left" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>Here is the <a href="http://blog.rudestar.net/wp-content/uploads/FindIntersection.zip">source code</a>.</p>
<p>Soon I plan to write about how to make an actual arm move based on this code but that is for another article.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rudiyardley.com/2010/01/how-to-calculate-the-intersection-of-two-circles-mathematically-in-actionscript/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What is Flex?</title>
		<link>http://blog.rudiyardley.com/2010/01/what-is-flex/</link>
		<comments>http://blog.rudiyardley.com/2010/01/what-is-flex/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 12:52:56 +0000</pubDate>
		<dc:creator>rudi</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>

		<guid isPermaLink="false">http://blog.rudestar.net/?p=351</guid>
		<description><![CDATA[I suppose sometimes as a Flex or Flash developer you are so immersed in the whole SWF ecosystem that occasionally you get asked a question that should be easy to answer but becomes difficult to explain to someone without a technical perspective.
The other day I was preparing a spec and getting a colleague to double [...]]]></description>
			<content:encoded><![CDATA[<p>I suppose sometimes as a Flex or Flash developer you are so immersed in the whole SWF ecosystem that occasionally you get asked a question that should be easy to answer but becomes difficult to explain to someone without a technical perspective.</p>
<p>The other day I was preparing a spec and getting a colleague to double check my correspondence. They brought up that the client likely did not know what Flex was and that I should be prepared to explain it to the client in the meeting we were tabled to have. My first reaction was fine until it dawned upon me that finding the words to describe flex for someone who only really understands flash as a scripting and animation technology may actually be a little difficult so thought I would share with you what I came up with as well as ask for opinions on the matter.</p>
<p>Here are a few possible answers:</p>
<ol>
<li>Flex is a collection of compilers that output SWF bitecode</li>
<li>Flex is a framework that is based on MXML as a meta-language for forming SWF bytecode</li>
<li>The Flex framework uses both MXML and a bunch of custom Actionscript classes to define the various visual and non-visual elements of Rich Applications</li>
<li>Flex makes building Rich applications with Flash faster by leveraging the use of standard user interface components and layout method</li>
</ol>
<p>Any other thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rudiyardley.com/2010/01/what-is-flex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to collision detection &amp; 2D physics</title>
		<link>http://blog.rudiyardley.com/2009/11/introduction-to-collision-detection-2d-physics/</link>
		<comments>http://blog.rudiyardley.com/2009/11/introduction-to-collision-detection-2d-physics/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 05:44:55 +0000</pubDate>
		<dc:creator>rudi</dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Game development]]></category>
		<category><![CDATA[Scripted Animation]]></category>
		<category><![CDATA[Physics]]></category>

		<guid isPermaLink="false">http://blog.rudestar.net/?p=147</guid>
		<description><![CDATA[This is an introductory tutorial on collision detection and physics. Creating 2D physics is often daunting to the beginner flash programmer but as you will soon see it is really not that hard so long as you break everything down into small steps. Here we are going to create a world and populate it with [...]]]></description>
			<content:encoded><![CDATA[<p>This is an introductory tutorial on collision detection and physics. Creating 2D physics is often daunting to the beginner flash programmer but as you will soon see it is really not that hard so long as you break everything down into small steps. Here we are going to create a world and populate it with a realistic bouncing ball:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld5.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld5.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
 
<p>The concepts required here may look daunting but all that needs to be required are the following:</p>
<ul>
<li>Velocity</li>
<li>Wall Collision Detection</li>
<li>Friction</li>
<li>Gravity</li>
</ul>
<h2>Defining the world</h2>
<p>Lets start off by defining our bounds and our world as a class like so:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>package</li><li><span class="br0">&#123;</span></li><li>	import flash.display.Sprite;</li><li>	import flash.events.Event;</li><li>	import flash.geom.Rectangle;</li><li>&nbsp;</li><li>	<span class="br0">&#91;</span>SWF<span class="br0">&#40;</span>width=&quot;530&quot;, height=&quot;397&quot;, frameRate=&quot;30&quot;, backgroundColor=&quot;#EEEEEE&quot;<span class="br0">&#41;</span><span class="br0">&#93;</span></li><li>	public class BallWorld extends Sprite</li><li>	<span class="br0">&#123;</span></li><li>		public function BallWorld<span class="br0">&#40;</span><span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			var world:World = new World<span class="br0">&#40;</span>530,397<span class="br0">&#41;</span>;</li><li>			addChild<span class="br0">&#40;</span>world<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li>&nbsp;</li><li>import flash.display.Sprite;</li><li>import flash.events.Event;</li><li>import flash.geom.Rectangle;</li><li>import flash.events.MouseEvent;</li><li>&nbsp;</li><li>class World extends Sprite</li><li><span class="br0">&#123;</span></li><li>&nbsp;</li><li>	public function World<span class="br0">&#40;</span>w:Number, h:Number<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		var backing:Sprite;</li><li>		backing = new Sprite<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		backing.graphics.lineStyle<span class="br0">&#40;</span>1,0xAAAAAA<span class="br0">&#41;</span>;</li><li>		backing.graphics.beginFill<span class="br0">&#40;</span>0xFFFFFF<span class="br0">&#41;</span>;</li><li>		backing.graphics.drawRect<span class="br0">&#40;</span>0,0,400,300<span class="br0">&#41;</span>;</li><li>		backing.x = w/2 - backing.width/<span style="">2</span>;</li><li>		backing.y = h/2 - backing.height/<span style="">2</span>;</li><li>		addChild<span class="br0">&#40;</span>backing<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>		var ball:Ball;</li><li>		ball = new Ball<span class="br0">&#40;</span>20<span class="br0">&#41;</span>;</li><li>		ball.x = w/<span style="">2</span>;</li><li>		ball.y = h/<span style="">2</span>;</li><li>		addChild<span class="br0">&#40;</span>ball<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li>&nbsp;</li><li>class Ball extends Sprite</li><li><span class="br0">&#123;</span></li><li>	public var radius:Number = <span style="">20</span>;	//	circle radius</li><li>&nbsp;</li><li>	public function Ball<span class="br0">&#40;</span>rad:Number<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		//	Apply params</li><li>		radius = rad;</li><li>&nbsp;</li><li>		//	Draw Ball</li><li>		graphics.lineStyle<span class="br0">&#40;</span>1,0xAAAAAA<span class="br0">&#41;</span>;</li><li>		graphics.beginFill<span class="br0">&#40;</span>0xA9C065<span class="br0">&#41;</span>;</li><li>		graphics.drawCircle<span class="br0">&#40;</span>0,0,radius<span class="br0">&#41;</span>;</li><li>		graphics.endFill<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_2" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld1.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld1.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
</p>
<p>Here we start with a World class that contains a backing sprite and a Ball Sprite which we have placed in the middle of the bounds. This tute is all about creating some realistic movement based on basic physics so lets get the ball to move.</p>
<h2>Velocity</h2>
<p>Within the physical world moving objects have a velocity which represents a distance moved over time. In Actionscript, we have a frame ticker which represents time so once every frame we can add the velocity to the coordinate position of our sprite to give the appearance of movement. Velocity in physics is given as a vector but in Actionscript we can provide it as two separate values for each coordinate. Lets add velocity to our ball:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>class Ball extends Sprite</li><li><span class="br0">&#123;</span></li><li>	public var vx:Number = <span style="">0</span>;		//	velocity x</li><li>	public var vy:Number = <span style="">0</span>;		//	velocity y</li><li>	public var radius:Number = <span style="">20</span>;	//	circle radius</li><li>&nbsp;</li><li>	public function Ball<span class="br0">&#40;</span>rad:Number<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		//	Apply params</li><li>		radius = rad;</li><li>&nbsp;</li><li>		//	Draw Ball</li><li>		graphics.lineStyle<span class="br0">&#40;</span>1,0xAAAAAA<span class="br0">&#41;</span>;</li><li>		graphics.beginFill<span class="br0">&#40;</span>0xA9C065<span class="br0">&#41;</span>;</li><li>		graphics.drawCircle<span class="br0">&#40;</span>0,0,radius<span class="br0">&#41;</span>;</li><li>		graphics.endFill<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>		//	Add Listeners</li><li>		addEventListener<span class="br0">&#40;</span>Event.ENTER_FRAME, onFrame<span class="br0">&#41;</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	private function onFrame<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li>	<span class="br0">&#123;</span></li><li>		//	Apply Velocity to Position</li><li>		x += vx;</li><li>		y += vy;</li><li>&nbsp;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />
Notice nothing much has happened. Our Ball is still sitting in the center of the stage and not moving. The reason it isn&#8217;t moving is because we have given it an initial velocity of 0 for both the x and y directions. Lets give this a number value of lets say 5. Add the following to our World class:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>...</li><li>var ball:Ball;</li><li>ball = new Ball<span class="br0">&#40;</span>20<span class="br0">&#41;</span>;</li><li>ball.x = w/<span style="">2</span>;</li><li>ball.y = h/<span style="">2</span>;</li><li>&nbsp;</li><li>//	Initial Velocity</li><li>ball.vx = <span style="">5</span>;</li><li>ball.vy = <span style="">5</span>;</li><li>...</li></ol></div></pre><!--END_DEVFMTCODE--><br />
Which gives us this:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_3" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld2.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld2.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>Bingo! the ball is moving but it is hardly realistic. Firstly the ball leaves the bounds almost immediately so we need to provide some collision detection and to constrain it to the given bounds.</p>
<h2>Wall Collision Detection</h2>
<p>Let&#8217;s add the following handler and variable to our Ball class:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>private var bounds:Rectangle;</li><li>...</li><li>public function Ball<span class="br0">&#40;</span>rad:Number<span class="br0">&#41;</span></li><li><span class="br0">&#123;</span></li><li>...</li><li>	//	Add Listeners</li><li>	addEventListener<span class="br0">&#40;</span>Event.ENTER_FRAME, onFrame<span class="br0">&#41;</span>;</li><li>	addEventListener<span class="br0">&#40;</span>Event.ADDED, onAdded<span class="br0">&#41;</span>;</li><li><span class="br0">&#125;</span></li><li>...</li><li>private function onAdded<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li><span class="br0">&#123;</span></li><li>	world = parent as World;</li><li>	bounds = world.bounds;</li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />
This is going to listen for when we add our ball to the world and at that instance get the properties of our world and apply them to the ball animation.</p>
<p>now add the following to our frame routine:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>private function onFrame<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li><span class="br0">&#123;</span></li><li>	//	Use a temp var for x and y to increase performance</li><li>	var tx:Number = x;</li><li>	var ty:Number = y;</li><li>&nbsp;</li><li>	//	Collision Detection with right wall</li><li>	if<span class="br0">&#40;</span>tx + vx &amp;gt; bounds.right - radius<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		tx = bounds.right - radius;</li><li>		vx *= -<span style="">1</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	//	Collision Detection with left wall</li><li>	if<span class="br0">&#40;</span>tx + vx &amp;lt; bounds.left + radius<span class="br0">&#41;</span> 	<span class="br0">&#123;</span></li><li> 		tx = bounds.left + radius;</li><li> 		vx *= -<span style="">1</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>&nbsp;&nbsp;	//	Collision Detection with floor</li><li>	if<span class="br0">&#40;</span>ty + vy &amp;gt; bounds.bottom - radius<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		ty = bounds.bottom - radius;</li><li>		vy *= -<span style="">1</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	//	Collision Detection with ceiling</li><li>	if<span class="br0">&#40;</span>ty + vy &amp;lt; bounds.top + radius<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		ty = bounds.top + radius;</li><li>		vy *= -<span style="">1</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	//	Apply Velocity to tx and ty</li><li>	tx += vx;</li><li>	ty += vy;</li><li>&nbsp;</li><li>	//	Render the change</li><li>	x = tx;</li><li>	y = ty;</li><li>&nbsp;</li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />
Lastly we need to alter our World class to provide us with the bounds property containing the bounds to constrict the ball to. So lets move our backing instance to become a private instance variable and access its getBounds method for the bounds of the world.<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>class World extends Sprite</li><li><span class="br0">&#123;</span></li><li>...</li><li>	private var backing:Sprite;</li><li>...</li><li>	public function get bounds<span class="br0">&#40;</span><span class="br0">&#41;</span>:Rectangle</li><li>	<span class="br0">&#123;</span></li><li>		return backing.getBounds<span class="br0">&#40;</span>this<span class="br0">&#41;</span>;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--><br />
Within the frame script we are now checking to see if the object has moved beyond the boundary given by the bounds Rectangle. If the bounds have been exceeded for any given direction the direction is reversed based on the boundary exceeded.</p>
<p>Here we also use a temporary variable to make it so that x is only set at the end of the frame script and is only necessary for performance reasons but is a good habit to get into since it is good to keep data and render separate.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_4" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld3.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld3.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>So now we have our ball flying away within our bounding box but the movement doesn&#8217;t look particularly real as we haven&#8217;t added any of the common physical forces to our object such as friction or gravity.</p>
<h2>Adding Friction</h2>
<p>To add air friction we simply need to multiply the velocity by a given amount between 0 and 1 every frame ie:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>//	Air Dampening</li><li>vx *= .99;</li><li>vy *= .99;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
This leaves us with something that looks like the following:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_5" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld4.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld4.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<h2>Gravity</h2>
<p>The last thing to do is add gravity to simulate the natural pull towards the ground by simply adding to the downward velocity every frame:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>//	Air Dampening</li><li>vx *= .99;</li><li>vy *= .99;	</li><li>&nbsp;</li><li>//	Gravity</li><li>vy += <span style="">1</span>;	</li><li>&nbsp;</li><li>//	Apply Velocity to tx and ty</li><li>tx += vx;</li><li>ty += vy;</li><li>&nbsp;</li><li>//	Render the change</li><li>x = tx;</li><li>y = ty;</li></ol></div></pre><!--END_DEVFMTCODE--><br />
After moving the gravity and friction properties to belong to the World we are left with the following full source code:<br />
<!--DEVFMTCODE--><pre class="devcodeblock" title=""><div class="devcodeoverflow"><ol><li>package</li><li><span class="br0">&#123;</span></li><li>	import flash.display.Sprite;</li><li>	import flash.events.Event;</li><li>	import flash.geom.Rectangle;</li><li>&nbsp;</li><li>	<span class="br0">&#91;</span>SWF<span class="br0">&#40;</span>width=&quot;530&quot;, height=&quot;397&quot;, frameRate=&quot;30&quot;, backgroundColor=&quot;#EEEEEE&quot;<span class="br0">&#41;</span><span class="br0">&#93;</span></li><li>	public class BallWorld extends Sprite</li><li>	<span class="br0">&#123;</span></li><li>		public function BallWorld<span class="br0">&#40;</span><span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			var world:World = new World<span class="br0">&#40;</span>530,397<span class="br0">&#41;</span>;</li><li>			addChild<span class="br0">&#40;</span>world<span class="br0">&#41;</span>;</li><li>		<span class="br0">&#125;</span></li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li>&nbsp;</li><li>import flash.display.Sprite;</li><li>import flash.events.Event;</li><li>import flash.geom.Rectangle;</li><li>import flash.events.MouseEvent;</li><li>&nbsp;</li><li>class World extends Sprite</li><li><span class="br0">&#123;</span></li><li>	private var backing:Sprite;</li><li>	public var friction:Number;</li><li>	public var gravity:Number;</li><li>&nbsp;</li><li>	public function World<span class="br0">&#40;</span>w:Number, h:Number<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		friction = <span style="">0.95</span>;</li><li>		gravity = <span style="">1</span>;</li><li>&nbsp;</li><li>		backing = new Sprite<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>		backing.graphics.lineStyle<span class="br0">&#40;</span>1,0xAAAAAA<span class="br0">&#41;</span>;</li><li>		backing.graphics.beginFill<span class="br0">&#40;</span>0xFFFFFF<span class="br0">&#41;</span>;</li><li>		backing.graphics.drawRect<span class="br0">&#40;</span>0,0,400,300<span class="br0">&#41;</span>;</li><li>		backing.x = w/2 - backing.width/<span style="">2</span>;</li><li>		backing.y = h/2 - backing.height/<span style="">2</span>;</li><li>		addChild<span class="br0">&#40;</span>backing<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>		var ball:Ball;</li><li>		ball = new Ball<span class="br0">&#40;</span>20<span class="br0">&#41;</span>;</li><li>		ball.x = w/<span style="">2</span>;</li><li>		ball.y = h/<span style="">2</span>;</li><li>&nbsp;</li><li>		//	Initial Velocity</li><li>		ball.vx = <span style="">5</span>;</li><li>		ball.vy = <span style="">5</span>;</li><li>&nbsp;</li><li>		addChild<span class="br0">&#40;</span>ball<span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	public function get bounds<span class="br0">&#40;</span><span class="br0">&#41;</span>:Rectangle</li><li>	<span class="br0">&#123;</span></li><li>		return backing.getBounds<span class="br0">&#40;</span>this<span class="br0">&#41;</span>;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li><li>&nbsp;</li><li>class Ball extends Sprite</li><li><span class="br0">&#123;</span></li><li>	public var vx:Number = <span style="">0</span>;		//	velocity x</li><li>	public var vy:Number = <span style="">0</span>;		//	velocity y</li><li>	public var radius:Number = <span style="">20</span>;	//	circle radius</li><li>	private var bounds:Rectangle;</li><li>	private var friction:Number;</li><li>	private var gravity:Number;</li><li>&nbsp;</li><li>	public function Ball<span class="br0">&#40;</span>rad:Number<span class="br0">&#41;</span></li><li>	<span class="br0">&#123;</span></li><li>		//	Apply params</li><li>		radius = rad;</li><li>&nbsp;</li><li>		//	Draw Ball</li><li>		graphics.lineStyle<span class="br0">&#40;</span>1,0xAAAAAA<span class="br0">&#41;</span>;</li><li>		graphics.beginFill<span class="br0">&#40;</span>0xA9C065<span class="br0">&#41;</span>;</li><li>		graphics.drawCircle<span class="br0">&#40;</span>0,0,radius<span class="br0">&#41;</span>;</li><li>		graphics.endFill<span class="br0">&#40;</span><span class="br0">&#41;</span>;</li><li>&nbsp;</li><li>		//	Add Listeners</li><li>		addEventListener<span class="br0">&#40;</span>Event.ENTER_FRAME, onFrame<span class="br0">&#41;</span>;</li><li>		addEventListener<span class="br0">&#40;</span>Event.ADDED, onAdded<span class="br0">&#41;</span>;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	private function onAdded<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li>	<span class="br0">&#123;</span></li><li>		var world:World = parent as World;</li><li>		bounds = world.bounds;</li><li>		friction = world.friction;</li><li>		gravity = world.gravity;</li><li>	<span class="br0">&#125;</span></li><li>&nbsp;</li><li>	private function onFrame<span class="br0">&#40;</span>e:Event<span class="br0">&#41;</span>:void</li><li>	<span class="br0">&#123;</span></li><li>		//	Use a temp var for x and y to increase performance</li><li>		var tx:Number = x;</li><li>		var ty:Number = y;</li><li>&nbsp;</li><li>		//	Collision Detection with right wall</li><li>		if<span class="br0">&#40;</span>tx + vx &amp;gt; bounds.right - radius<span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			tx = bounds.right - radius;</li><li>			vx *= -<span style="">1</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	Collision Detection with left wall</li><li>		if<span class="br0">&#40;</span>tx + vx &amp;lt; bounds.left + radius<span class="br0">&#41;</span> 		<span class="br0">&#123;</span> 			tx = bounds.left + radius; 			vx *= -<span style="">1</span>; 		<span class="br0">&#125;</span> 		 		//	Collision Detection with floor 		if<span class="br0">&#40;</span>ty + vy &amp;gt; bounds.bottom - radius<span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			ty = bounds.bottom - radius;</li><li>			vy *= -<span style="">1</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	Collision Detection with ceiling</li><li>		if<span class="br0">&#40;</span>ty + vy &amp;lt; bounds.top + radius<span class="br0">&#41;</span></li><li>		<span class="br0">&#123;</span></li><li>			ty = bounds.top + radius;</li><li>			vy *= -<span style="">1</span>;</li><li>		<span class="br0">&#125;</span></li><li>&nbsp;</li><li>		//	Air Dampening</li><li>		vx *= friction;</li><li>		vy *= friction;	</li><li>&nbsp;</li><li>		vy += gravity;</li><li>&nbsp;</li><li>		//	Apply Velocity to tx and ty</li><li>		tx += vx;</li><li>		ty += vy;</li><li>&nbsp;</li><li>		//	Render the change</li><li>		x = tx;</li><li>		y = ty;</li><li>&nbsp;</li><li>	<span class="br0">&#125;</span></li><li><span class="br0">&#125;</span></li></ol></div></pre><!--END_DEVFMTCODE--></p>
<p>As you can see by adding gravity we substantially increase the reality factor of the motion.</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_6" width="530" height="398">
      <param name="movie" value="http://blog.rudestar.net/wp-content/uploads/BallWorld5.swf" />
      <param name="allowfullscreen" value="true" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://blog.rudestar.net/wp-content/uploads/BallWorld5.swf" width="530" height="398" allowfullscreen="true">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
 
]]></content:encoded>
			<wfw:commentRss>http://blog.rudiyardley.com/2009/11/introduction-to-collision-detection-2d-physics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

