<?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>Lon Hosford&#039;s Bitbox</title>
	<atom:link href="http://www.lonhosford.com/lonblog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.lonhosford.com/lonblog</link>
	<description>Lon (Alonzo) Hosford&#039;s Professional Consulting Blog</description>
	<lastBuildDate>Fri, 03 Feb 2012 00:55:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Tap, Move, Shake: Turning Your Game Ideas into iPhone &amp; iPad Apps</title>
		<link>http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/</link>
		<comments>http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/#comments</comments>
		<pubDate>Sun, 22 Jan 2012 21:51:10 +0000</pubDate>
		<dc:creator>Lon Hosford</dc:creator>
				<category><![CDATA[Gaming]]></category>
		<category><![CDATA[IPhone]]></category>
		<category><![CDATA[Objective C]]></category>
		<category><![CDATA[XCode]]></category>

		<guid isPermaLink="false">http://www.lonhosford.com/lonblog/?p=2845</guid>
		<description><![CDATA[Todd Moore&#8217;s new book, Tap, Move, Shake: Turning Your Game Ideas into iPhone &#038; iPad Apps, is currently the best choice for getting started with writing and publishing IOS games. A key feature is that the apps in the book are IN THE APP STORE. Never saw that trick before and I think is a [...]]]></description>
			<content:encoded><![CDATA[<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/" send="true" width="450" show_faces="true" font=""></fb:like><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p>Todd Moore&#8217;s new book, <strong><a href="http://www.amazon.com/gp/product/1449303455/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1449303455">Tap, Move, Shake: Turning Your Game Ideas into iPhone &#038; iPad Apps</a></strong>, is currently the best choice for getting started with writing and publishing IOS games. </p>
<p>A key feature is that <strong>the apps in the book are IN THE APP STORE</strong>. Never saw that trick before and I think is a standard for anyone writing IOS books. I actually followed the steps of creating an app I could download suffice it had a tad more flash in the store.</p>
<div class="wp-caption alignleft" style="width: 131px"><a href="http://www.amazon.com/gp/product/1449303455/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1449303455" target="_blank"><img  src="http://ecx.images-amazon.com/images/I/51erZvLUPaL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA300_SH20_OU01_.jpg" alt="Tap, Move, Shake: Turning Your Game Ideas into iPhone &#038; iPad Apps" width="121" height="160" class="  " title="Tap, Move, Shake: Turning Your Game Ideas into iPhone &#038; iPad Apps"/></a><p class="wp-caption-text">Tap, Move, Shake: Turning Your Game Ideas into iPhone &#038; iPad Apps</p></div>
<p>This is the first book I have seen in XCode/ObjectiveC that takes the submission to the App store as important a learning step as is the process of writing code. I loved the give and take App store rejection emails that provided a lot of insight for anyone who is going to submit an app the first time.</p>
<p>Also insightful is the special effort in giving the coder who is light on media creation great chapters on creating graphics and sound. Links provided are well researched.</p>
<p>On the wish list for me was not to dismiss ARC (Automatic Reference Counting) at the onset. Gee the book kinda assumes the beginner and ARC leans to that. But I suspect a case of examples completed at a time Apple was busy upsetting the cart for writers in progress.</p>
<p>The chapters are extremely well thought out especially the progression of development with the sections in each chapter. </p>
<p>I think you need a basic skill in XCode and Objective C to follow the book. XCode is introduced nicely for beginners and Objective C is learned more by example and less by explanation. I could not have solved some bugs without a basic skill in Objective C. The architecture of IOS app is explained well. I loved the clarity of explaining the bootstrap of an IOS app. I finally got it!</p>
<p>The book covers EVERYTHING you need from setting up for development, coding, basic testing, resource creation, app submission and even app marketing. All at a very clear to the point approach. The book examples make you feel you are starting at the beginning because they are from the gaming industry beginnings tuned to the phone.</p>
<p>This is 254 page book that has a good number of images taking up pages. Compared to 3 and 4 inch opus magnum IOS books out there that are OMGs difficult to hold open on the desk or in a lounge chair, Todd gets a great deal done as a focused writer. Cutting content is key. I rather buy more books than have big monsters.</p>
<p>Want to get started in IOS gaming without a gaming engine or better understand your gaming engine, then do this book.</p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/" send="true" width="450" show_faces="true" font=""></fb:like></p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:comments href="http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/" num_posts="3" width="500"></fb:comments></p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<!-- Place this render call where appropriate --><br />
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lonhosford.com/lonblog/2012/01/22/tap-move-shake-turning-your-game-ideas-into-iphone-ipad-apps/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kobold2D XCode 4 Introduction Tutorial Lesson 7 &#8211; Display Score Using Graphic Glyphs</title>
		<link>http://www.lonhosford.com/lonblog/2011/12/27/kobold2d-xcode-4-introduction-tutorial-lesson-7-display-score-using-graphic-glyphs/</link>
		<comments>http://www.lonhosford.com/lonblog/2011/12/27/kobold2d-xcode-4-introduction-tutorial-lesson-7-display-score-using-graphic-glyphs/#comments</comments>
		<pubDate>Tue, 27 Dec 2011 16:17:54 +0000</pubDate>
		<dc:creator>Lon Hosford</dc:creator>
				<category><![CDATA[Kobold2D]]></category>
		<category><![CDATA[Accelerometer]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Gaming]]></category>

		<guid isPermaLink="false">http://www.lonhosford.com/lonblog/?p=2797</guid>
		<description><![CDATA[&#60;== Lesson 6 &#124;&#124; Lesson 8 ==&#62; The scoring in this game needs a display. Up to this point you can only see the score in the XCode console window. The scoring data you are tracking is the number of attempts and the number of hits. The number of attempts is a class property that [...]]]></description>
			<content:encoded><![CDATA[<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/">&lt;== Lesson 6</a> || <a href="#" onclick = "alert('12/27/11: Lesson 8 - Add Levels\nIN PROGRESS. CHECK BACK LATER');return false">Lesson 8 ==&gt; </a>  </p>
<p>The scoring in this game needs a display. Up to this point you can only see the score in the XCode console window. <img class="alignleft" src="http://www.lonhosford.com/images/kobold2d/common/blog_article.png" alt="" width="160" height="218" /><br />
<div class="wp-caption alignright" style="width: 131px"><a href="http://www.amazon.com/gp/product/1430238135/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1430238135" target="_blank"><img  src="https://images-na.ssl-images-amazon.com/images/I/415NHKs30yL._SL160_.jpg" alt="Learn cocos2D Game Development" width="121" height="160" class="  " title="Learn cocos2D Game Development"/></a><p class="wp-caption-text">Learn cocos2D Game Development</p></div> </p>
<p>The scoring data you are tracking is the number of attempts and the number of hits. The number of attempts is a class property that increments each time a new moving target is started from the top of the screen.</p>
<p>The number of hits is incremented each time the player intercepts the moving target. </p>
<p>Using the number of attempts and number of hits, we can display three values. One is the total attempts. The second is the number of misses which is the number of hits minus the number of misses. The third value is the number of hits. </p>
<p>We will just display them at the top middle of the screen with a colon separating each value. </p>
<p>For the score display, we will use a graphic containing the exact characters we need. Those characters are the digits 0 to 9, a space and a colon. </p>
<div class="wp-caption aligncenter" style="width: 560px"><img class=" " style="border: 0pt none;" src="http://www.lonhosford.com/images/kobold2d/lesson_07/ipad_running.png" alt="" width="550" height="423" /><p class="wp-caption-text">Finished Lesson Running on IPad2 Simulator</p></div>
<p>To display the graphic characters you will use the Cocos2D <a href="http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_label_b_m_font.html" target = _blank">CCLabelBMFont</a> class. You can pack all the characters into one file. Then the CCLabelBMFont treats each character like a <a href="http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_sprite.html" target = _blank">CCSprite</a>. This means that each individual character can be rotated, scaled, translated, and tinted like other Cocos2D CCSprite objects. We do not have much more of a need other than to place them on the screen and layer them underneath the game pieces.</p>
<p><a href="http://glyphdesigner.71squared.com/" target = _blank">Glyph Designer</a> is the tool I use to create the files needed for <a href="http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_label_b_m_font.html" target = _blank">CCLabelBMFont</a>. There is a fee for Glyph Designer. I have not used another tool like it but the $30 US was a great value and the online tutorial videos made getting use out of it a snap. Plus Cocos2D is a product Glyph Designer supports.</p>
<p><strong>Lesson Downloads</strong></p>
<ol>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson07/introduction_tutorial_lesson07_assets.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson07/introduction_tutorial_lesson07_assets.zip">Game piece images, score glyph files including Glyph Designer project file and sound for project</a>.</li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson07/introduction_tutorial_common.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson07/introduction_tutorial_common.zip">IPhone images for project</a>. Icons and splash screen.</li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson07/Intro_Tutorial_Lesson_07.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson07/Intro_Tutorial_Lesson_07.zip">Completed Project</a>. This is built in Kobold2d 1.0.1.</li>
</ol>
<p><strong>Step 1 &#8211; Build an Empty-Project Template</strong></p>
<p>You can continue with the <a href="http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/">Lesson 6</a> project and make changes noted here. <div class="wp-caption alignleft" style="width: 221px"><img class=" " style="border: 0pt none;" src="http://www.lonhosford.com/images/kobold2d/lesson_07/project_files_resources.png" alt="" width="211" height="303" /><p class="wp-caption-text">Listing of Projectfiles->Resources Group</p></div></p>
<p>Otherwise the steps for creating this project from an Empty-Project template are the same as <a href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/">Lesson 1</a> except to substitute Lesson 7 for Lesson 1 in the project name and to include the red_ball.png, red_ball-hd.png and explosion.caf files when you add the game pieces. The explosion.caf goes in same group as the images. Then you can use the code presented here.</p>
<p>In either case your Projectfiles->Resources group should have the files shown in the image to the left.</p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p><strong>Step 2 &#8211; Set Properties in config.lua</strong></p>
<p>There are no new configuration properties from Lesson 6. Complete config.lua file is included here for your copy convenience.</p>
<pre class="brush: jscript; collapse: true; light: false; toolbar: true;">
--[[
* Kobold2D™ --- http://www.kobold2d.org
*
* Copyright (c) 2010-2011 Steffen Itterheim.
* Released under MIT License in Germany (LICENSE-Kobold2D.txt).
--]]

--[[
* Need help with the KKStartupConfig settings?
* ------ http://www.kobold2d.com/x/ygMO ------
--]]

local config =
{
    KKStartupConfig =
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = &quot;GameLayer&quot;,

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,

        EnableUserInteraction = YES,
        EnableMultiTouch = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,
        EnableGLViewNodeHitTesting = NO,
        EnableStatusBar = NO,

        -- Orientation &amp; Autorotation
        DeviceOrientation = DeviceOrientation.LandscapeLeft,
        AutorotationType = Autorotation.None,
        ShouldAutorotateToLandscapeOrientations = NO,
        ShouldAutorotateToPortraitOrientations = NO,
        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,

        -- Ad setup
        EnableAdBanner = NO,
        PlaceBannerOnBottom = YES,
        LoadOnlyPortraitBanners = NO,
        LoadOnlyLandscapeBanners = NO,
        AdProviders = &quot;iAd, AdMob&quot;,	-- comma seperated list -&gt; &quot;iAd, AdMob&quot; means: use iAd if available, otherwise AdMob
        AdMobRefreshRate = 15,
        AdMobFirstAdDelay = 5,
        AdMobPublisherID = &quot;YOUR_ADMOB_PUBLISHER_ID&quot;, -- how to get an AdMob Publisher ID: http://developer.admob.com/wiki/PublisherSetup
        AdMobTestMode = YES,

        -- Mac OS specific settings
        AutoScale = NO,
        AcceptsMouseMovedEvents = NO,
        WindowFrame = RectMake(1024-640, 768-480, 640, 480),
        EnableFullScreen = NO,
    },
}

return config
</pre>
<p><strong>Step 3 &#8211; GameLayer.h </strong></p>
<p>Line 18 shows the  <a href="http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_label_b_m_font.html" target = _blank">CCLabelBMFont</a> object for displaying the score.</p>
<pre class="brush: objc; highlight: [18];">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;kobold2d.h&quot;

@interface GameLayer : CCLayer
{
    CCSprite* player;
    CGPoint playerVelocity;
    CCSprite* movingTarget;
	float movingTargetMoveDuration;
    int totalAttempts;
    int totalHits;
    CCLabelBMFont* scoreLabel;
}
@end
</pre>
<p><strong>Step 4 &#8211; GameLayer.m: Add initScore and setScore Methods for Score Display</strong></p>
<p>Complete GameLayer.m file is included here for your copy convenience. </p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;
#import &quot;SimpleAudioEngine.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
-(void) initScore;
-(void) setScore;
@end

// Velocity deceleration
const float deceleration = 0.4f;
// Accelerometer sensitivity (higher = more sensitive)
const float sensitivity = 6.0f;
// Maximum velocity
const float maxVelocity = 100.0f;

@implementation GameLayer

-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Preload the sound effect into memory so there's no delay when playing it the first time.
		[[SimpleAudioEngine sharedEngine] preloadEffect:@&quot;explosion.caf&quot;];
        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label z:-1];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 7&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2 z:-1];
        // The score label initialized
        [self initScore];
        // Add below game action
		[self addChild:scoreLabel z:-1];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
-(void) dealloc
{
#ifndef KK_ARC_ENABLED
	[super dealloc];
#endif // KK_ARC_ENABLED
}
#pragma mark Player Movement
-(void) acceleratePlayerWithX:(double)xAcceleration
{
    // Adjust velocity based on current accelerometer acceleration
    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);
    // Limit the maximum velocity of the player sprite, in both directions (positive &amp; negative values)
    if (playerVelocity.x &gt; maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x &lt; -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }
}
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x &lt; leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x &gt; rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos;
    // Collision check
    [self checkForCollision];
}
#pragma mark MovingTarget

-(void) initMovingTarget
{
    NSLog(@&quot;initMovingTarget&quot;);
    // This is the image
	movingTarget = [CCSprite spriteWithFile:@&quot;red_ball.png&quot;];
    // Add CCSprite for movingTarget
    [self addChild:movingTarget z:0 tag:2];
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
    movingTargetMoveDuration = 4.0f;
   	// Unschedule the selector just in case. If it isn't scheduled it won't do anything.
	[self unschedule:@selector(movingTargetUpdate:)];
	// Schedule the movingTarget update logic to run at the given interval.
	[self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Update score to display increment in totalAttempts
    [self setScore];
    // Increment total attempts to hit a moving target.
    totalAttempts ++;
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) movingTargetUpdate:(ccTime)delta
{
    // CCSprite-&gt;CCNode no sequence of actions running.
    if ([movingTarget numberOfRunningActions] == 0)
    {
        NSLog(@&quot;movingTargetUpdate&quot;);
        // Determine below screen position.
        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( [movingTarget texture].contentSize.height));
        // CCAction to move a CCNode object to the position x,y based on position.
        CCMoveTo* moveEnd = [CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];
        // Call back function for the action.
        CCCallFuncN* callEndMovingTargetSequence = [CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];
        // Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.
        CCSequence* sequence = [CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];
        // Run the sequence.
        [movingTarget runAction:sequence];
    }
}
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    [movingTarget stopAllActions];
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];

}
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        // Play a sound effect
        [[SimpleAudioEngine sharedEngine] playEffect:@&quot;explosion.caf&quot;];
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalHits, totalAttempts);
        [self setScore];
        [self endMovingTargetSequence];
    }
}
#pragma mark score
-(void) initScore
{
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Load font information.
    scoreLabel = [CCLabelBMFont labelWithString:@&quot;+0 : 0&quot; fntFile:@&quot;score_glyphs.fnt&quot;];
    scoreLabel.position = CGPointMake(screenSize.width / 2, screenSize.height);
    // Set anchorPoint y position to align with the top of screen.
    scoreLabel.anchorPoint = CGPointMake(0.5f, 1.0f);
}
-(void) setScore
{
    [scoreLabel setString:[NSString stringWithFormat:@&quot;%i : %i : %i&quot;, totalAttempts,totalAttempts-totalHits, totalHits]];
}
@end
</pre>
<p>Two private methods initScore and setScore are declared on lines 17 and 18.</p>
<pre class="brush: objc; highlight: [17,18];">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;
#import &quot;SimpleAudioEngine.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
-(void) initScore;
-(void) setScore;
@end
</pre>
<p>The CCLabelBMFont could be declared in the init method. I choose a separate method to stop the growth of the init method and also organize related coded into reusable pieces.</p>
<p>That called for getting the screen center again so the score can be centered. </p>
<p>The score_glyphs.fnt file is human readable and contains the information CCLabelBMFont needs to break out the images in score_glyphs.png. Both score_glyphs.fnt and score_glyphs.png where exported from Glyph Designer.  </p>
<p>Line 235 sets up the storing score so the score_glyphs.png is cached.</p>
<p>The anchorPoint property is a convenient way to offset the y position. The Cocos2d documentation recommends not to change the defaults: &#8220;All inner characters are using an anchorPoint of (0.5f, 0.5f) and it is not recommend to change it because it might affect the rendering&#8221;. However it works so we will use it.</p>
<p>Line 242 displays the three score values of totalAttempts, the number of misses and the totalHits.</p>
<pre class="brush: objc; first-line: 230;">
#pragma mark score
-(void) initScore
{
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Load font information.
    scoreLabel = [CCLabelBMFont labelWithString:@&quot;0 : 0 : 0&quot; fntFile:@&quot;score_glyphs.fnt&quot;];
    scoreLabel.position = CGPointMake(screenSize.width / 2, screenSize.height);
    // Set anchorPoint y position to align with the top of screen.
    scoreLabel.anchorPoint = CGPointMake(0.5f, 1.0f);
}
-(void) setScore
{
    [scoreLabel setString:[NSString stringWithFormat:@&quot;%i : %i : %i&quot;, totalAttempts,totalAttempts-totalHits, totalHits]];
}
</pre>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<strong>Step 5 &#8211; GameLayer.m: Initialize the Score in the init Method</strong></p>
<p>On line 66 the score added to the game layer.</p>
<p>On lines 57 and 64 the game information overlay is moved back so the moving target appears over them.</p>
<p>Line 59 updates the subtitle which helps keep track what we are looking at when testing.</p>
<pre class="brush: objc; first-line: 30; highlight: [57,59,64,66];">
-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Preload the sound effect into memory so there's no delay when playing it the first time.
		[[SimpleAudioEngine sharedEngine] preloadEffect:@&quot;explosion.caf&quot;];
        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label z:-1];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 7&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2 z:-1];
        // The score label initialized
        [self initScore];
        // Add below game action
		[self addChild:scoreLabel z:-1];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
</pre>
<p><strong>Step 6 &#8211; GameLayer.m: Update Score For Misses</strong></p>
<p>Line 155 updates the score before incrementing the number of attempts on line 157. If we do it after, the misses would show a value of 1 more than actual each time a new moving target it put into play.</p>
<pre class="brush: objc; first-line: 151; highlight: [155];">
-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Update score to display increment in totalAttempts
    [self setScore];
    // Increment total attempts to hit a moving target.
    totalAttempts ++;
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}
</pre>
<p><strong>Step 7 &#8211; GameLayer.m: Update Score For Hits</strong></p>
<p>On each hit you want to update the score. The checkForCollision method handles the hits for this game.</p>
<p>You are already displaying score data in the checkForCollision method. So you just need to drop in a call to the setScore method on line 226 just after the class property totalHits is incremented. </p>
<pre class="brush: objc; first-line: 205; highlight: [226];">
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        // Play a sound effect
        [[SimpleAudioEngine sharedEngine] playEffect:@&quot;explosion.caf&quot;];
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalHits, totalAttempts);
        [self setScore];
        [self endMovingTargetSequence];
    }
}
</pre>
<p>That should give you a good starting point for displaying a graphic glyph score.</p>
<p><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/">&lt;== Lesson 6</a> || <a href="#" onclick = "alert('12/27/11: Lesson 8 - Add Levels\nIN PROGRESS. CHECK BACK LATER');return false">Lesson 8 ==&gt; </a>  </p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like></p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:comments href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" num_posts="3" width="500"></fb:comments></p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<!-- Place this render call where appropriate --><br />
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lonhosford.com/lonblog/2011/12/27/kobold2d-xcode-4-introduction-tutorial-lesson-7-display-score-using-graphic-glyphs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kobold2D XCode 4 Introduction Tutorial Lesson 6 &#8211; Add Collision Sound Effect</title>
		<link>http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/</link>
		<comments>http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 22:45:04 +0000</pubDate>
		<dc:creator>Lon Hosford</dc:creator>
				<category><![CDATA[Kobold2D]]></category>
		<category><![CDATA[Accelerometer]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[CocosDenshion]]></category>
		<category><![CDATA[Gaming]]></category>

		<guid isPermaLink="false">http://www.lonhosford.com/lonblog/?p=2780</guid>
		<description><![CDATA[&#60;== Lesson 5 &#124;&#124; Lesson 7 ==&#62; So far you can see the XCode console window reports the collisions between the player and moving target. Now is time to add some sound. Audio is not integrated into Cocos2D and so a library is required. Fortunately CocosDenshion is an audio library with IOS gaming in mind [...]]]></description>
			<content:encoded><![CDATA[<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/">&lt;== Lesson 5</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/27/kobold2d-xcode-4-introduction-tutorial-lesson-7-display-score-using-graphic-glyphs/" >Lesson 7 ==&gt; </a>  </p>
<p>So far you can see the XCode console window reports the collisions between the player and moving target. <img class="alignleft" src="http://www.lonhosford.com/images/kobold2d/common/blog_article.png" alt="" width="160" height="218" /><br />
<div class="wp-caption alignright" style="width: 131px"><a href="http://www.amazon.com/gp/product/1430238135/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1430238135" target="_blank"><img  src="https://images-na.ssl-images-amazon.com/images/I/415NHKs30yL._SL160_.jpg" alt="Learn cocos2D Game Development" width="121" height="160" class="  " title="Learn cocos2D Game Development"/></a><p class="wp-caption-text">Learn cocos2D Game Development</p></div> </p>
<p>Now is time to add some sound. Audio is not integrated into Cocos2D and so a library is required.  Fortunately <a href="http://cocos2d-iphone.org/wiki/doku.php/cocosdenshion:faq" target = "_blank">CocosDenshion</a> is an audio library with IOS gaming in mind and is a part of Kobold2D. CocosDenshion is referred to as SimpleAudioEngine in the code.</p>
<p>The file format for playing background sound with CocosDenshion is mp3. For short sound effects, the format recommendation is 16 bit mono wave files for uncompressed audio and IMA4 for lossy compressed audio. You can read more on formats and sound quality choices at <a href="http://cocos2d-iphone.org/wiki/doku.php/cocosdenshion:faq" target = "_blank">CocosDenshion</a> .</p>
<div class="wp-caption aligncenter" style="width: 560px"><img class=" " style="border: 0pt none;" src="http://www.lonhosford.com/images/kobold2d/lesson_06/ipad_running.png" alt="" width="550" height="423" /><p class="wp-caption-text">Finished Lesson Running on IPad2 Simulator</p></div>
<p><strong>Lesson Downloads</strong></p>
<ol>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson06/introduction_tutorial_lesson06_assets.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson06/introduction_tutorial_lesson06_assets.zip">Game piece images and sound for project</a></li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson06/introduction_tutorial_common.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson06/introduction_tutorial_common.zip">IPhone images for project</a>. Icons and splash screen.</li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson06/Intro_Tutorial_Lesson_06.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson06/Intro_Tutorial_Lesson_06.zip">Completed Project</a>. This is built in Kobold2d 1.0.1.</li>
</ol>
<p><strong>Step 1 &#8211; Build an Empty-Project Template</strong></p>
<p>You can continue with the <a href="http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/">Lesson 5</a> project and make changes noted here. Otherwise the steps for creating this project from an Empty-Project template are the same as <a href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/">Lesson 1</a> except to substitute Lesson 6 for Lesson 1 in the project name and to include the red_ball.png, red_ball-hd.png and explosion.caf files when you add the game pieces. The explosion.caf goes in same group as the images. Then you can use the code presented here.</p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p><strong>Step 2 &#8211; Set Properties in config.lua</strong></p>
<p>There are no new configuration properties from Lesson 5. Complete config.lua file is included here for your copy convenience.</p>
<pre class="brush: jscript; collapse: true; light: false; toolbar: true;">
--[[
* Kobold2D™ --- http://www.kobold2d.org
*
* Copyright (c) 2010-2011 Steffen Itterheim.
* Released under MIT License in Germany (LICENSE-Kobold2D.txt).
--]]

--[[
* Need help with the KKStartupConfig settings?
* ------ http://www.kobold2d.com/x/ygMO ------
--]]

local config =
{
    KKStartupConfig =
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = &quot;GameLayer&quot;,

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,

        EnableUserInteraction = YES,
        EnableMultiTouch = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,
        EnableGLViewNodeHitTesting = NO,
        EnableStatusBar = NO,

        -- Orientation &amp; Autorotation
        DeviceOrientation = DeviceOrientation.LandscapeLeft,
        AutorotationType = Autorotation.None,
        ShouldAutorotateToLandscapeOrientations = NO,
        ShouldAutorotateToPortraitOrientations = NO,
        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,

        -- Ad setup
        EnableAdBanner = NO,
        PlaceBannerOnBottom = YES,
        LoadOnlyPortraitBanners = NO,
        LoadOnlyLandscapeBanners = NO,
        AdProviders = &quot;iAd, AdMob&quot;,	-- comma seperated list -&gt; &quot;iAd, AdMob&quot; means: use iAd if available, otherwise AdMob
        AdMobRefreshRate = 15,
        AdMobFirstAdDelay = 5,
        AdMobPublisherID = &quot;YOUR_ADMOB_PUBLISHER_ID&quot;, -- how to get an AdMob Publisher ID: http://developer.admob.com/wiki/PublisherSetup
        AdMobTestMode = YES,

        -- Mac OS specific settings
        AutoScale = NO,
        AcceptsMouseMovedEvents = NO,
        WindowFrame = RectMake(1024-640, 768-480, 640, 480),
        EnableFullScreen = NO,
    },
}

return config
</pre>
<p><strong>Step 3 &#8211; GameLayer.h </strong></p>
<p>There are no changes from Lesson 5 so the entire code is here for your copy and paste convenience.</p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;kobold2d.h&quot;

@interface GameLayer : CCLayer
{
    CCSprite* player;
    CGPoint playerVelocity;
    CCSprite* movingTarget;
	float movingTargetMoveDuration;
    int totalAttempts;
    int totalHits;
}
@end
</pre>
<p><strong>Step 4 &#8211; Include the SimpleAudioEngine Library</strong></p>
<p>Complete GameLayer.m file is included here for your copy convenience. I will focus on the code changes to accommodate the collision sounds.</p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;
#import &quot;SimpleAudioEngine.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
@end

// Velocity deceleration
const float deceleration = 0.4f;
// Accelerometer sensitivity (higher = more sensitive)
const float sensitivity = 6.0f;
// Maximum velocity
const float maxVelocity = 100.0f;

@implementation GameLayer

-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Preload the sound effect into memory so there's no delay when playing it the first time.
		[[SimpleAudioEngine sharedEngine] preloadEffect:@&quot;explosion.caf&quot;];

        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 6&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
-(void) dealloc
{
#ifndef KK_ARC_ENABLED
	[super dealloc];
#endif // KK_ARC_ENABLED
}
#pragma mark Player Movement
-(void) acceleratePlayerWithX:(double)xAcceleration
{
    // Adjust velocity based on current accelerometer acceleration
    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);
    // Limit the maximum velocity of the player sprite, in both directions (positive &amp; negative values)
    if (playerVelocity.x &gt; maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x &lt; -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }
}
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x &lt; leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x &gt; rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos;
    // Collision check
    [self checkForCollision];
}
#pragma mark MovingTarget

-(void) initMovingTarget
{
    NSLog(@&quot;initMovingTarget&quot;);
    // This is the image
	movingTarget = [CCSprite spriteWithFile:@&quot;red_ball.png&quot;];
    // Add CCSprite for movingTarget
    [self addChild:movingTarget z:0 tag:2];
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
    movingTargetMoveDuration = 4.0f;
   	// Unschedule the selector just in case. If it isn't scheduled it won't do anything.
	[self unschedule:@selector(movingTargetUpdate:)];
	// Schedule the movingTarget update logic to run at the given interval.
	[self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Increment total attempts to hit a moving target.
    totalAttempts ++;
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) movingTargetUpdate:(ccTime)delta
{
    // CCSprite-&gt;CCNode no sequence of actions running.
    if ([movingTarget numberOfRunningActions] == 0)
    {
        NSLog(@&quot;movingTargetUpdate&quot;);
        // Determine below screen position.
        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( [movingTarget texture].contentSize.height));
        // CCAction to move a CCNode object to the position x,y based on position.
        CCMoveTo* moveEnd = [CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];
        // Call back function for the action.
        CCCallFuncN* callEndMovingTargetSequence = [CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];
        // Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.
        CCSequence* sequence = [CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];
        // Run the sequence.
        [movingTarget runAction:sequence];
    }
}
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    [movingTarget stopAllActions];
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
}
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        // Play a sound effect
        [[SimpleAudioEngine sharedEngine] playEffect:@&quot;explosion.caf&quot;];
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalAttempts, totalHits);
        [self endMovingTargetSequence];
    }
}
@end
</pre>
<p>First the sound effect library is needed. Line 9 accomplishes that for you.</p>
<pre class="brush: objc; highlight: [9];">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;
#import &quot;SimpleAudioEngine.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
@end
</pre>
<p><strong>Step 5 &#8211; Preload the Collision Sound Effect</strong></p>
<p>Next you can preload the sound effect file to avoid a delay the first time it is played. The init method is the perfect place to do the preloading and line 36 shows how it is done with SimpleAudioEngine.</p>
<pre class="brush: objc; first-line: 28; highlight: [36];">
-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Preload the sound effect into memory so there's no delay when playing it the first time.
		[[SimpleAudioEngine sharedEngine] preloadEffect:@&quot;explosion.caf&quot;];

        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 6&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
</pre>
<p><strong>Step 6 &#8211; Play the Collision Sound Effect</strong></p>
<p>Playing the sound effect is done in the checkForCollision method and is a single line of code on line 215.</p>
<pre class="brush: objc; first-line: 197; highlight: [215];">
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        // Play a sound effect
        [[SimpleAudioEngine sharedEngine] playEffect:@&quot;explosion.caf&quot;];
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalAttempts, totalHits);
        [self endMovingTargetSequence];
    }
}
</pre>
<p>You should be all set to hear crashes as you tilt your IPad or IPhone and try to intercept our falling target.</p>
<p><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/">&lt;== Lesson 5</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/27/kobold2d-xcode-4-introduction-tutorial-lesson-7-display-score-using-graphic-glyphs/" >Lesson 7 ==&gt; </a>  </p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like></p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:comments href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" num_posts="3" width="500"></fb:comments></p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<!-- Place this render call where appropriate --><br />
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kobold2D XCode 4 Introduction Tutorial Lesson 5 &#8211; Add Collision Detection</title>
		<link>http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/</link>
		<comments>http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 19:18:46 +0000</pubDate>
		<dc:creator>Lon Hosford</dc:creator>
				<category><![CDATA[Kobold2D]]></category>
		<category><![CDATA[Accelerometer]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Gaming]]></category>

		<guid isPermaLink="false">http://www.lonhosford.com/lonblog/?p=2759</guid>
		<description><![CDATA[&#60;== Lesson 4 &#124;&#124; Lesson 6 ==&#62; Now its time to detect the collision of the moving target and the player. For this game, the collision is a good thing as that is the goal. So we will call collisions between the player and the moving target a hit. To plan ahead, you will also [...]]]></description>
			<content:encoded><![CDATA[<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/">&lt;== Lesson 4</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/">Lesson 6 ==&gt; </a>  </p>
<p>Now its time to detect the collision of the moving target and the player. <img class="alignleft" src="http://www.lonhosford.com/images/kobold2d/common/blog_article.png" alt="" width="160" height="218" /><br />
<div class="wp-caption alignright" style="width: 131px"><a href="http://www.amazon.com/gp/product/1430238135/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1430238135" target="_blank"><img  src="https://images-na.ssl-images-amazon.com/images/I/415NHKs30yL._SL160_.jpg" alt="Learn cocos2D Game Development" width="121" height="160" class="  " title="Learn cocos2D Game Development"/></a><p class="wp-caption-text">Learn cocos2D Game Development</p></div> </p>
<p>For this game, the collision is a good thing as that is the goal. So we will call collisions between the player and the moving target a hit. </p>
<p>To plan ahead, you will also add a counter to detect the number of hits. For now you will just display that value in the XCode console window.  That will help debug the collision detection and set up for use of that value.</p>
<div class="wp-caption aligncenter" style="width: 560px"><img class=" " style="border: 0pt none;" src="http://www.lonhosford.com/images/kobold2d/lesson_05/ipad_running.png" alt="" width="550" height="423" /><p class="wp-caption-text">Finished Lesson Running on IPad2 Simulator</p></div>
<p><strong>Lesson Downloads</strong></p>
<ol>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson05/introduction_tutorial_lesson05_images.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson05/introduction_tutorial_lesson05_images.zip">Game piece images for project</a></li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson05/introduction_tutorial_common.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson05/introduction_tutorial_common.zip">IPhone images for project</a>. Icons and splash screen.</li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson05/Intro_Tutorial_Lesson_05.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson05/Intro_Tutorial_Lesson_05.zip">Completed Project</a>. This is built in Kobold2d 1.0.1.</li>
</ol>
<p><strong>Step 1 &#8211; Build an Empty-Project Template</strong></p>
<p>You can continue with the <a href="http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/">Lesson 4</a> project and make changes noted here. Otherwise the steps for creating this project from an Empty-Project template are the same as <a href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/">Lesson 1</a> except to substitute Lesson 5 for Lesson 1 in the project name and to include the red_ball.png and red_ball-hd.png files when you add the game pieces. Then you can use the code presented here.<br />
<div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p><strong>Step 2 &#8211; Set Properties in config.lua</strong></p>
<p>There are no new configuration properties from Lesson 4. Complete config.lua file is included here for your copy convenience.</p>
<pre class="brush: jscript; collapse: true; light: false; toolbar: true;">
--[[
* Kobold2D™ --- http://www.kobold2d.org
*
* Copyright (c) 2010-2011 Steffen Itterheim.
* Released under MIT License in Germany (LICENSE-Kobold2D.txt).
--]]

--[[
* Need help with the KKStartupConfig settings?
* ------ http://www.kobold2d.com/x/ygMO ------
--]]

local config =
{
    KKStartupConfig =
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = &quot;GameLayer&quot;,

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,

        EnableUserInteraction = YES,
        EnableMultiTouch = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,
        EnableGLViewNodeHitTesting = NO,
        EnableStatusBar = NO,

        -- Orientation &amp; Autorotation
        DeviceOrientation = DeviceOrientation.LandscapeLeft,
        AutorotationType = Autorotation.None,
        ShouldAutorotateToLandscapeOrientations = NO,
        ShouldAutorotateToPortraitOrientations = NO,
        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,

        -- Ad setup
        EnableAdBanner = NO,
        PlaceBannerOnBottom = YES,
        LoadOnlyPortraitBanners = NO,
        LoadOnlyLandscapeBanners = NO,
        AdProviders = &quot;iAd, AdMob&quot;,	-- comma seperated list -&gt; &quot;iAd, AdMob&quot; means: use iAd if available, otherwise AdMob
        AdMobRefreshRate = 15,
        AdMobFirstAdDelay = 5,
        AdMobPublisherID = &quot;YOUR_ADMOB_PUBLISHER_ID&quot;, -- how to get an AdMob Publisher ID: http://developer.admob.com/wiki/PublisherSetup
        AdMobTestMode = YES,

        -- Mac OS specific settings
        AutoScale = NO,
        AcceptsMouseMovedEvents = NO,
        WindowFrame = RectMake(1024-640, 768-480, 640, 480),
        EnableFullScreen = NO,
    },
}

return config
</pre>
<p><strong>Step 3 &#8211; GameLayer.h </strong></p>
<p>Added are two variables to track the play. Line 16 is keeping track of the total times a moving target was started to descend down the screen.</p>
<p>Line 17 tracks the number of times the moving target and the player collided.</p>
<pre class="brush: objc; highlight: [16,17];">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;kobold2d.h&quot;

@interface GameLayer : CCLayer
{
    CCSprite* player;
    CGPoint playerVelocity;
    CCSprite* movingTarget;
	float movingTargetMoveDuration;
    int totalAttempts;
    int totalHits;
}
@end
</pre>
<p><strong>Step 4 &#8211; Add checkForCollision Private Method</strong></p>
<p>Complete GameLayer.m file is included here for your copy convenience. I will focus on the code changes to accommodate the collision detection.</p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
@end

// Velocity deceleration
const float deceleration = 0.4f;
// Accelerometer sensitivity (higher = more sensitive)
const float sensitivity = 6.0f;
// Maximum velocity
const float maxVelocity = 100.0f;

@implementation GameLayer

-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 5&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
-(void) dealloc
{
#ifndef KK_ARC_ENABLED
	[super dealloc];
#endif // KK_ARC_ENABLED
}
#pragma mark Player Movement
-(void) acceleratePlayerWithX:(double)xAcceleration
{
    // Adjust velocity based on current accelerometer acceleration
    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);
    // Limit the maximum velocity of the player sprite, in both directions (positive &amp; negative values)
    if (playerVelocity.x &gt; maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x &lt; -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }
}
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x &lt; leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x &gt; rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos;
    // Collision check
    [self checkForCollision];
}
#pragma mark MovingTarget

-(void) initMovingTarget
{
    NSLog(@&quot;initMovingTarget&quot;);
    // This is the image
	movingTarget = [CCSprite spriteWithFile:@&quot;red_ball.png&quot;];
    // Add CCSprite for movingTarget
    [self addChild:movingTarget z:0 tag:2];
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
    movingTargetMoveDuration = 4.0f;
   	// Unschedule the selector just in case. If it isn't scheduled it won't do anything.
	[self unschedule:@selector(movingTargetUpdate:)];
	// Schedule the movingTarget update logic to run at the given interval.
	[self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Increment total attempts to hit a moving target.
    totalAttempts ++;
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) movingTargetUpdate:(ccTime)delta
{
    // CCSprite-&gt;CCNode no sequence of actions running.
    if ([movingTarget numberOfRunningActions] == 0)
    {
        NSLog(@&quot;movingTargetUpdate&quot;);
        // Determine below screen position.
        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( [movingTarget texture].contentSize.height));
        // CCAction to move a CCNode object to the position x,y based on position.
        CCMoveTo* moveEnd = [CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];
        // Call back function for the action.
        CCCallFuncN* callEndMovingTargetSequence = [CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];
        // Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.
        CCSequence* sequence = [CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];
        // Run the sequence.
        [movingTarget runAction:sequence];
    }
}
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    [movingTarget stopAllActions];
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
}
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalAttempts, totalHits);
        [self endMovingTargetSequence];
    }
}
@end
</pre>
<p>First set of changes are in the declaration of a new private method checkForCollision.</p>
<pre class="brush: objc; first-line: 8; highlight: [15];">
#import &quot;GameLayer.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
-(void) checkForCollision;
@end
</pre>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<strong>Step 5 &#8211; Initialize Scoring Properties and Update Subtitle</strong></p>
<p>The scoring properties are initialized on lines 35 and 37.</p>
<p>Line 54 clarifies the lesson in the subtitle.</p>
<pre class="brush: objc; first-line: 27; highlight: [35,37,54];">
-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Initialize the total attempts to hit a moving target.
        totalAttempts = 0;
        // Initialize the total hits
        totalHits = 0;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 5&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
</pre>
<p><strong>Step 6 &#8211; Call the Collision Detection Method</strong></p>
<p>Each time the game data is updated you also can check for any collisions. The update method is called for each iteration in the game. </p>
<p>You can just put the message for the checkForCollision, shown on line 122, at the end. By the end of checkForCollision the player and moving targets are in their new positions and a perfect place to check for an overlap.</p>
<pre class="brush: objc; first-line: 90; highlight: [122];">
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x &lt; leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x &gt; rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos;
    // Collision check
    [self checkForCollision];
}
</pre>
<p><strong>Step 7 &#8211; Kill The Moving Target Actions</strong></p>
<p>The endMovingTargetSequence method can be called once a collision is detected. It is set up to clean up the current moving target and call the startMovingTargetSequence for the next moving target.</p>
<p>However endMovingTargetSequence presents a timing issue between the update of the game and the number of times the moving target actions occur. For each game update you will observe multiple calls for the moving target CCMoveTo moveEnd  action defined in movingTargetUpdate. </p>
<p>That creates an opening for multiple hits before line 181 unschedule gets fired. So the moving target will proceed through the position of the player and each update will detect a collision.</p>
<p>The solution is to add  the <a href="http://www.cocos2d-iphone.org/api-ref/2.0.0/interface_c_c_node.html#a24f2916259df943e3f13cdd702673962" target = "_blank">stopAllActions</a> method is from Cocos2D CCNode class. Making stopAllActions the first line results in immediate termination of all actions for the moving target. See line 179.</p>
<pre class="brush: objc; first-line: 176; highlight: [179];">
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    [movingTarget stopAllActions];
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
}
</pre>
<p><strong>Step 8 &#8211; Count the Total Moving Targets</strong></p>
<p>The startMovingTargetSequence is fired each time a new moving target is added. This is where, see line 146, to increment the counter for the number of moving targets.</p>
<pre class="brush: objc; first-line: 142; highlight: [146];">
-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Increment total attempts to hit a moving target.
    totalAttempts ++;
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}
</pre>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<strong>Step 9 &#8211; Add Collision Detection Method</strong></p>
<p>The checkForCollision method is our new method that handles collisions between the moving target and the player.</p>
<p>The process is twofold. One to compute the distance that defines a collision. Lines 196 &#8211; 203 do that. The measurement is based on the graphics and their center registration point and any offset you want to add to that based on observing the collisions. </p>
<p> Second part of the collision detection process is computing the actual dist and and line 205 does that for us.</p>
<p>Line 208 defines a code block if there is hit and in that code block the totalHits counter is incremented and the endMovingTargetSequence method is called to remove the moving target.</p>
<pre class="brush: objc; first-line: 193;">
#pragma mark Collision Check
-(void) checkForCollision
{
	// Size of the player and target. Both are assumed squares so width suffices.
	float playerImageSize = [player texture].contentSize.width;
	float targetImageSize = [movingTarget texture].contentSize.width;
	// Compute their radii. Tweak based on drawing and observations.
	float playerCollisionRadius = playerImageSize *.4;
	float targetCollisionRadius = targetImageSize *.4;
	// This collision distance will roughly equal the image shapes.
	float maxCollisionDistance = playerCollisionRadius + targetCollisionRadius;
    // Distance between two points.
    float actualDistance = ccpDistance(player.position, movingTarget.position);

    // Are the two objects closer than allowed?
    if (actualDistance &lt; maxCollisionDistance)
    {
        totalHits++;
        NSLog(@&quot;HIT! Total attempts: %i. Total hits: %i&quot;, totalAttempts, totalHits);
        [self endMovingTargetSequence];
    }
}
</pre>
<p><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone><br />
<a href="http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/">&lt;== Lesson 4</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/23/kobold2d-xcode-4-introduction-tutorial-lesson-6-add-collision-sound-effect/">Lesson 6 ==&gt; </a>  </p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like></p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:comments href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" num_posts="3" width="500"></fb:comments></p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<!-- Place this render call where appropriate --><br />
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Kobold2D XCode 4 Introduction Tutorial Lesson 4 &#8211; Progressively Increase Moving Target Speed</title>
		<link>http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/</link>
		<comments>http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 02:14:09 +0000</pubDate>
		<dc:creator>Lon Hosford</dc:creator>
				<category><![CDATA[Kobold2D]]></category>
		<category><![CDATA[Accelerometer]]></category>
		<category><![CDATA[Cocos2d]]></category>
		<category><![CDATA[Gaming]]></category>
		<category><![CDATA[XCode]]></category>

		<guid isPermaLink="false">http://www.lonhosford.com/lonblog/?p=2674</guid>
		<description><![CDATA[&#60;== Lesson 3 &#124;&#124; Lesson 5 ==&#62; This is a short lesson that adds a tad of challenge to trying to intercept the moving target. The challenge is to increase the speed of each iteration of the moving target. The movingTargetDuration property has the length of time to &#8220;fall&#8221; from the top of the screen [...]]]></description>
			<content:encoded><![CDATA[<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone></p>
<p><a href="http://www.lonhosford.com/lonblog/2011/12/20/kobold2d-xcode-4-introduction-tutorial-lesson-3-add-random-falling-target/">&lt;== Lesson 3</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/" >Lesson 5 ==&gt; </a>  </p>
<p>This is a short lesson that adds a tad of challenge to trying to intercept the moving target. <img class="alignleft" src="http://www.lonhosford.com/images/kobold2d/common/blog_article.png" alt="" width="160" height="218" /><br />
<div class="wp-caption alignright" style="width: 131px"><a href="http://www.amazon.com/gp/product/1430238135/ref=as_li_ss_tl?ie=UTF8&#038;tag=hosfordusa&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=1430238135" target="_blank"><img  src="https://images-na.ssl-images-amazon.com/images/I/415NHKs30yL._SL160_.jpg" alt="Learn cocos2D Game Development" width="121" height="160" class="  " title="Learn cocos2D Game Development"/></a><p class="wp-caption-text">Learn cocos2D Game Development</p></div> </p>
<p>The challenge is to increase the speed of each iteration of the moving target. The movingTargetDuration property has the length of time to &#8220;fall&#8221; from the top of the screen to the bottom. Progressively decreasing that value will increase the rate of movement for each interval. </p>
<p>However you eventually need to tweak game challenges so they are not impossible while remaining doable with practice. In this case a moving target duration below 2 appears to be close to the limit of impossible for the IPad in landscape mode. </p>
<p>Your testing may conclude differently that the speed could get higher. This is just a lesson and hopefully opens you to thoughts for varying the challenge. For example the decrease in the duration could be random number from a range say 0.0 &#8211; 0.2. Or you could have a random hyper change in the duration for one iteration only.</p>
<p>One other item that can vary the challenge is game levels. Our tutorial is limited to one level at this lesson. If more levels are added, then variations on the moving target speed, direction and size could be possible properties to add challenge.</p>
<div class="wp-caption aligncenter" style="width: 560px"><img class=" " style="border: 0pt none;" src="http://www.lonhosford.com/images/kobold2d/lesson_04/ipad_running.png" alt="" width="550" height="423" /><p class="wp-caption-text">Finished Lesson Running on IPad2 Simulator</p></div>
<p><strong>Lesson Downloads</strong></p>
<ol>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson04/introduction_tutorial_lesson04_images.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson04/introduction_tutorial_lesson04_images.zip">Game piece images for project</a></li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson04/introduction_tutorial_common.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson04/introduction_tutorial_common.zip">IPhone images for project</a>. Icons and splash screen.</li>
<li>
<a onclick="javascript: pageTracker._trackPageview('/downloads/kobold2d/intro_tutorial/lesson04/Intro_Tutorial_Lesson_04.zip'); " href="http://www.lonhosford.com/content/kobold2d/intro_tutorial/lesson04/Intro_Tutorial_Lesson_04.zip">Completed Project</a>. This is built in Kobold2d 1.0.1.</li>
</ol>
<p><strong>Step 1 &#8211; Build an Empty-Project Template</strong></p>
<p>You can continue with the <a href="http://www.lonhosford.com/lonblog/2011/12/20/kobold2d-xcode-4-introduction-tutorial-lesson-3-add-random-falling-target/">Lesson 3</a> project and make changes noted here. Otherwise the steps for creating this project from an Empty-Project template are the same as <a href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/">Lesson 1</a> except to substitute Lesson 4 for Lesson 1 in the project name and to include the red_ball.png and red_ball-hd.png files when you add the game pieces. Then you can use the code presented here.<br />
<div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div></p>
<p><strong>Step 2 &#8211; Set Properties in config.lua</strong></p>
<p>There are no new configuration properties from Lesson 3. Complete config.lua file is included here for your copy convenience.</p>
<pre class="brush: jscript; collapse: true; light: false; toolbar: true;">
--[[
* Kobold2D™ --- http://www.kobold2d.org
*
* Copyright (c) 2010-2011 Steffen Itterheim.
* Released under MIT License in Germany (LICENSE-Kobold2D.txt).
--]]

--[[
* Need help with the KKStartupConfig settings?
* ------ http://www.kobold2d.com/x/ygMO ------
--]]

local config =
{
    KKStartupConfig =
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = &quot;GameLayer&quot;,

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,

        EnableUserInteraction = YES,
        EnableMultiTouch = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,
        EnableGLViewNodeHitTesting = NO,
        EnableStatusBar = NO,

        -- Orientation &amp; Autorotation
        DeviceOrientation = DeviceOrientation.LandscapeLeft,
        AutorotationType = Autorotation.None,
        ShouldAutorotateToLandscapeOrientations = NO,
        ShouldAutorotateToPortraitOrientations = NO,
        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,

        -- Ad setup
        EnableAdBanner = NO,
        PlaceBannerOnBottom = YES,
        LoadOnlyPortraitBanners = NO,
        LoadOnlyLandscapeBanners = NO,
        AdProviders = &quot;iAd, AdMob&quot;,	-- comma seperated list -&gt; &quot;iAd, AdMob&quot; means: use iAd if available, otherwise AdMob
        AdMobRefreshRate = 15,
        AdMobFirstAdDelay = 5,
        AdMobPublisherID = &quot;YOUR_ADMOB_PUBLISHER_ID&quot;, -- how to get an AdMob Publisher ID: http://developer.admob.com/wiki/PublisherSetup
        AdMobTestMode = YES,

        -- Mac OS specific settings
        AutoScale = NO,
        AcceptsMouseMovedEvents = NO,
        WindowFrame = RectMake(1024-640, 768-480, 640, 480),
        EnableFullScreen = NO,
    },
}

return config
</pre>
<p><strong>Step 3 &#8211; GameLayer.h </strong></p>
<p>No changes from Lesson 3. Complete GameLayer.h file is included here for your copy convenience.</p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;kobold2d.h&quot;

@interface GameLayer : CCLayer
{
    CCSprite* player;
    CGPoint playerVelocity;
    CCSprite* movingTarget;
	float movingTargetMoveDuration;
}
@end
</pre>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<strong>Step 4 &#8211; Reduce Moving Target Animation Duration</strong></p>
<p>Complete GameLayer.m file is included here for your copy convenience. We will just look at the code change up ahead for the endMovingTargetSequence method.</p>
<pre class="brush: objc; collapse: true; light: false; toolbar: true;">
/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim.
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import &quot;GameLayer.h&quot;

@interface GameLayer (PrivateMethods)
-(void) initMovingTarget;
-(void) movingTargetUpdate:(ccTime)delta;
-(void) startMovingTargetSequence;
-(void) endMovingTargetSequence;
@end

// Velocity deceleration
const float deceleration = 0.4f;
// Accelerometer sensitivity (higher = more sensitive)
const float sensitivity = 6.0f;
// Maximum velocity
const float maxVelocity = 100.0f;

@implementation GameLayer

-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Graphic for player
        player = [CCSprite spriteWithFile:@&quot;green_ball.png&quot;];
		[self addChild:player z:0 tag:1];
        // Position player
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot;
                                               fontName:@&quot;Arial&quot;
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@&quot;Lesson 4&quot;
                                                fontName:@&quot;Arial&quot;
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Seed random number generator
        srandom((UInt32)time(NULL));
        // Initialize our moving target.
        [self initMovingTarget];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
-(void) dealloc
{
#ifndef KK_ARC_ENABLED
	[super dealloc];
#endif // KK_ARC_ENABLED
}
#pragma mark Player Movement
-(void) acceleratePlayerWithX:(double)xAcceleration
{
    // Adjust velocity based on current accelerometer acceleration
    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);
    // Limit the maximum velocity of the player sprite, in both directions (positive &amp; negative values)
    if (playerVelocity.x &gt; maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x &lt; -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }
}
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x &lt; leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x &gt; rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos;
}
#pragma mark MovingTarget

-(void) initMovingTarget
{
    NSLog(@&quot;initMovingTarget&quot;);
    // This is the image
	movingTarget = [CCSprite spriteWithFile:@&quot;red_ball.png&quot;];
    // Add CCSprite for movingTarget
    [self addChild:movingTarget z:0 tag:2];
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
    movingTargetMoveDuration = 4.0f;
   	// Unschedule the selector just in case. If it isn't scheduled it won't do anything.
	[self unschedule:@selector(movingTargetUpdate:)];
	// Schedule the movingTarget update logic to run at the given interval.
	[self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) startMovingTargetSequence
{
    NSLog(@&quot;startMovingTargetSequence&quot;);
    // Get the window size
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Get the image size
    CGSize imageSize = [movingTarget texture].contentSize;
    // Generate a random x starting position with offsets for center registration point.
    int randomX = CCRANDOM_0_1() * (screenSize.width / imageSize.width);
    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);
    // Schedule the movingTarget update logic to run at the given interval.
    [self schedule:@selector(movingTargetUpdate:) interval:0.1f];
}

-(void) movingTargetUpdate:(ccTime)delta
{
    // CCSprite-&gt;CCNode no sequence of actions running.
    if ([movingTarget numberOfRunningActions] == 0)
    {
        NSLog(@&quot;movingTargetUpdate&quot;);
        // Determine below screen position.
        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( [movingTarget texture].contentSize.height));
        // CCAction to move a CCNode object to the position x,y based on position.
        CCMoveTo* moveEnd = [CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];
        // Call back function for the action.
        CCCallFuncN* callEndMovingTargetSequence = [CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];
        // Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.
        CCSequence* sequence = [CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];
        // Run the sequence.
        [movingTarget runAction:sequence];
    }
}
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
}

@end
</pre>
<p>The endMovingTargetSequence method is called when the moving target exits the bottom of the screen. That is set in the movingTargetUpdate method.</p>
<p>Line 173 of the endMovingTargetSequence method reduces the movingTargetMoveDuration class property by 0.1. </p>
<p>The movingTargetMoveDuration property starts at 4.0 in the initMovingTarget method.</p>
<p>Line 175 &#8211; 178 add a governor to prevent the duration from becoming less than 2.0. </p>
<p>As I mentioned earlier, you can be creative with ways to vary the moving target speed. </p>
<pre class="brush: objc; first-line: 167; highlight: [172,173,174,175,176,177,178];">
-(void) endMovingTargetSequence
{
    NSLog(@&quot;endMovingTargetSequence&quot;);
    // Terminate running the moveTargetUpdate interval.
    [self unschedule:@selector(movingTargetUpdate:)];
    // Decrease the moving target move duration to increase the speed.
    movingTargetMoveDuration -= 0.1f;
    // Moving target move duration is below 2 then hold at 2.
    if (movingTargetMoveDuration &lt; 2.0f)
    {
        movingTargetMoveDuration = 2.0f;
    }
    NSLog(@&quot;movingTargetMoveDuration: %f&quot;,movingTargetMoveDuration);
    // Set the starting position and start movingTarget play sequence
    [self startMovingTargetSequence];
}
</pre>
<p><!-- Place this tag where you want the +1 button to render --><br />
<g:plusone annotation="inline"></g:plusone><br />
<a href="http://www.lonhosford.com/lonblog/2011/12/20/kobold2d-xcode-4-introduction-tutorial-lesson-3-add-random-falling-target/">&lt;== Lesson 3</a> || <a href="http://www.lonhosford.com/lonblog/2011/12/22/kobold2d-xcode-4-introduction-tutorial-lesson-5-add-collision-detection/" >Lesson 5 ==&gt; </a>   </p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#appId=105467682877384&amp;xfbml=1"></script><fb:like href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" send="true" width="450" show_faces="true" font=""></fb:like></p>
<div id="fb-root"></div>
<p><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:comments href="http://www.lonhosford.com/lonblog/2011/12/18/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer/" num_posts="3" width="500"></fb:comments></p>
<p><div style = "text-align:center"><script type="text/javascript"><!--
google_ad_client = "pub-8926707286265620";
/* 300x250, created 7/29/10 */
google_ad_slot = "4548376258";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><br />
<!-- Place this render call where appropriate --><br />
<script type="text/javascript">
  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.lonhosford.com/lonblog/2011/12/21/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

