{"id":2673,"date":"2011-12-20T23:01:58","date_gmt":"2011-12-21T04:01:58","guid":{"rendered":"http:\/\/www.lonhosford.com\/lonblog\/?p=2673"},"modified":"2015-07-31T18:25:49","modified_gmt":"2015-07-31T23:25:49","slug":"kobold2d-xcode-4-introduction-tutorial-lesson-3-add-random-falling-target","status":"publish","type":"post","link":"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/20\/kobold2d-xcode-4-introduction-tutorial-lesson-3-add-random-falling-target\/","title":{"rendered":"Kobold2D XCode 4 Introduction Tutorial Lesson 3 &#8211; Add Random Falling Target"},"content":{"rendered":"<div id=\"fb-root\"><\/div>\n<p><script src=\"https:\/\/connect.facebook.net\/en_US\/all.js#appId=105467682877384&amp;xfbml=1\"><\/script><fb:like href=\"https:\/\/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 \/>\n<g:plusone annotation=\"inline\"><\/g:plusone><\/p>\n<p><a href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/19\/kobold2d-xcode-4-introduction-tutorial-lesson-2-set-landscape-orientation\/\">&lt;== Lesson 2<\/a>  || <a href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/21\/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed\/\" >Lesson 4 ==&gt; <\/a>  <\/p>\n<p>We have not discussed much about the nature of the game.  Believe me it is relatively routine. The green player will try to intercept a falling red target.<br \/>\n<img loading=\"lazy\" decoding=\"async\" class=\"alignleft\" src=\"https:\/\/www.lonhosford.com\/images\/kobold2d\/common\/blog_article.png\" alt=\"\" width=\"160\" height=\"218\" \/><figure style=\"width: 121px\" class=\"wp-caption alignright\"><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 loading=\"lazy\" decoding=\"async\"  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><figcaption class=\"wp-caption-text\">Learn cocos2D Game Development<\/figcaption><\/figure> <\/p>\n<p>The falling red target will start at random horizontal positions at the top of the screen and drop to the bottom of the screen. Only one red target falls at a time. The goal is to get the green player to intercept the falling red target.<\/p>\n<p>In this lesson, we will add the falling red target but will not handle the collision. However, you can get some practice trying for later when you add a collision with sound and points.<\/p>\n<figure style=\"width: 550px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\" \" style=\"border: 0pt none;\" src=\"https:\/\/www.lonhosford.com\/images\/kobold2d\/lesson_03\/ipad_running.png\" alt=\"\" width=\"550\" height=\"423\" \/><figcaption class=\"wp-caption-text\">Finished Lesson Running on IPad2 Simulator<\/figcaption><\/figure>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\n<strong>Lesson Downloads<\/strong><\/p>\n<ol>\n<li>\n<a onclick=\"javascript: pageTracker._trackPageview('\/downloads\/kobold2d\/intro_tutorial\/lesson03\/introduction_tutorial_lesson03_images.zip'); \" href=\"https:\/\/www.lonhosford.com\/content\/kobold2d\/intro_tutorial\/lesson03\/introduction_tutorial_lesson03_images.zip\">Game piece images for project<\/a><\/li>\n<li>\n<a onclick=\"javascript: pageTracker._trackPageview('\/downloads\/kobold2d\/intro_tutorial\/lesson03\/introduction_tutorial_common.zip'); \" href=\"https:\/\/www.lonhosford.com\/content\/kobold2d\/intro_tutorial\/lesson03\/introduction_tutorial_common.zip\">IPhone images for project<\/a>. Icons and splash screen.<\/li>\n<li>\n<a onclick=\"javascript: pageTracker._trackPageview('\/downloads\/kobold2d\/intro_tutorial\/lesson03\/Intro_Tutorial_Lesson_03.zip'); \" href=\"https:\/\/www.lonhosford.com\/content\/kobold2d\/intro_tutorial\/lesson03\/Intro_Tutorial_Lesson_03.zip\">Completed Project<\/a>. This is built in Kobold2d 1.0.1.<\/li>\n<\/ol>\n<p><strong>Step 1 &#8211; Build an Empty-Project Template<\/strong><\/p>\n<p>You can continue with the <a href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/19\/kobold2d-xcode-4-introduction-tutorial-lesson-2-set-landscape-orientation\/\">Lesson 2<\/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=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/18\/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer\/\">Lesson 1<\/a> except to substitute Lesson 3 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.<\/p>\n<p><strong>Step 2 &#8211; Set Properties in config.lua<\/strong><\/p>\n<p>There are no new property changes from lesson 2. All are included here for you to follow along.<\/p>\n<pre class=\"brush: jscript; collapse: true; light: false; title: ; toolbar: true; notranslate\" title=\"\">\r\n--&#x5B;&#x5B;\r\n* Kobold2D\u2122 --- http:\/\/www.kobold2d.org\r\n*\r\n* Copyright (c) 2010-2011 Steffen Itterheim. \r\n* Released under MIT License in Germany (LICENSE-Kobold2D.txt).\r\n--]]\r\n\r\n\r\n--&#x5B;&#x5B;\r\n* Need help with the KKStartupConfig settings?\r\n* ------ http:\/\/www.kobold2d.com\/x\/ygMO ------\r\n--]]\r\n\r\n\r\nlocal config =\r\n{\r\n    KKStartupConfig = \r\n    {\r\n        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended\r\n        FirstSceneClassName = &quot;GameLayer&quot;,\r\n\r\n        -- set the director type, and the fallback in case the first isn't available\r\n        DirectorType = DirectorType.DisplayLink,\r\n        DirectorTypeFallback = DirectorType.NSTimer,\r\n\r\n        MaxFrameRate = 60,\r\n        DisplayFPS = YES,\r\n\r\n        EnableUserInteraction = YES,\r\n        EnableMultiTouch = NO,\r\n\r\n        -- Render settings\r\n        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,\r\n        GLViewColorFormat = GLViewColorFormat.RGB565,\r\n        GLViewDepthFormat = GLViewDepthFormat.DepthNone,\r\n        GLViewMultiSampling = NO,\r\n        GLViewNumberOfSamples = 0,\r\n\r\n        Enable2DProjection = NO,\r\n        EnableRetinaDisplaySupport = YES,\r\n        EnableGLViewNodeHitTesting = NO,\r\n        EnableStatusBar = NO,\r\n\r\n        -- Orientation &amp; Autorotation\r\n        DeviceOrientation = DeviceOrientation.LandscapeRight,\r\n        AutorotationType = Autorotation.None,\r\n        ShouldAutorotateToLandscapeOrientations = NO,\r\n        ShouldAutorotateToPortraitOrientations = NO,\r\n        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,\r\n\r\n        -- Ad setup\r\n        EnableAdBanner = NO,\r\n        PlaceBannerOnBottom = YES,\r\n        LoadOnlyPortraitBanners = NO,\r\n        LoadOnlyLandscapeBanners = NO,\r\n        AdProviders = &quot;iAd, AdMob&quot;,\t-- comma seperated list -&gt; &quot;iAd, AdMob&quot; means: use iAd if available, otherwise AdMob\r\n        AdMobRefreshRate = 15,\r\n        AdMobFirstAdDelay = 5,\r\n        AdMobPublisherID = &quot;YOUR_ADMOB_PUBLISHER_ID&quot;, -- how to get an AdMob Publisher ID: http:\/\/developer.admob.com\/wiki\/PublisherSetup\r\n        AdMobTestMode = YES,\r\n\r\n        -- Mac OS specific settings\r\n        AutoScale = NO,\r\n        AcceptsMouseMovedEvents = NO,\r\n        WindowFrame = RectMake(1024-640, 768-480, 640, 480),\r\n        EnableFullScreen = NO,\r\n    },\r\n}\r\n\r\nreturn config\r\n\r\n<\/pre>\n<p><strong>Step 3 &#8211; Add Moving Target Properties to GameLayer.h File<\/strong><\/p>\n<p>A <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_sprite.html\" target = \"_blank\">CCSprite<\/a> Cocos2d object is responsible for our target shown on line 14. CCSprite represents a 2d image and inherits from <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_node.html\" target = \"_blank\">CCNode<\/a>. <\/p>\n<p>The movingTargetDuration float is the speed of the target fall from the top of the screen.<\/p>\n<pre class=\"brush: objc; highlight: [14,15]; title: ; notranslate\" title=\"\">\r\n\/*\r\n * Kobold2D\u2122 --- http:\/\/www.kobold2d.org\r\n *\r\n * Copyright (c) 2010-2011 Steffen Itterheim. \r\n * Released under MIT License in Germany (LICENSE-Kobold2D.txt).\r\n *\/\r\n\r\n#import &quot;kobold2d.h&quot;\r\n\r\n@interface GameLayer : CCLayer\r\n{\r\n    CCSprite* player;\r\n    CGPoint playerVelocity;\r\n    CCSprite* movingTarget;\r\n\tfloat movingTargetMoveDuration;\r\n}\r\n@end\r\n<\/pre>\n<p><strong>Step 4 &#8211; Integrate Moving Target Into to GameLayer.m File<\/strong><\/p>\n<p>I am going to discuss specific sections of the GameLayer.m file in this post. Meantime for the impatient, like me, here here is the full GameLayer.m source code for your copy and paste convenience.<\/p>\n<pre class=\"brush: objc; collapse: true; light: false; title: ; toolbar: true; notranslate\" title=\"\">\r\n\/*\r\n * Kobold2D\u2122 --- http:\/\/www.kobold2d.org\r\n *\r\n * Copyright (c) 2010-2011 Steffen Itterheim. \r\n * Released under MIT License in Germany (LICENSE-Kobold2D.txt).\r\n *\/\r\n\r\n#import &quot;GameLayer.h&quot;\r\n\r\n@interface GameLayer (PrivateMethods)\r\n-(void) initMovingTarget;\r\n-(void) movingTargetUpdate:(ccTime)delta;\r\n-(void) startMovingTargetSequence;\r\n-(void) endMovingTargetSequence;\r\n@end\r\n\r\n\/\/ Velocity deceleration\r\nconst float deceleration = 0.4f;\r\n\/\/ Accelerometer sensitivity (higher = more sensitive)\r\nconst float sensitivity = 6.0f;\r\n\/\/ Maximum velocity\r\nconst float maxVelocity = 100.0f;\r\n\r\n@implementation GameLayer\r\n\r\n-(id) init\r\n{\r\n\tif ((self = &#x5B;super init]))\r\n\t{\r\n        \/\/ Enable accelerometer input events.\r\n\t\t&#x5B;KKInput sharedInput].accelerometerActive = YES;\r\n\t\t&#x5B;KKInput sharedInput].acceleration.filteringFactor = 0.2f;\r\n        \/\/ Graphic for player\r\n        player = &#x5B;CCSprite spriteWithFile:@&quot;green_ball.png&quot;];\r\n\t\t&#x5B;self addChild:player z:0 tag:1];\r\n        \/\/ Position player        \r\n        CGSize screenSize = &#x5B;&#x5B;CCDirector sharedDirector] winSize];\r\n\t\tfloat imageHeight = &#x5B;player texture].contentSize.height;\r\n\t\tplayer.position = CGPointMake(screenSize.width \/ 2, imageHeight \/ 2);\r\n\t\tglClearColor(0.1f, 0.1f, 0.3f, 1.0f);\r\n\t\t\/\/ First line of title\r\n\t\tCCLabelTTF* label = &#x5B;CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot; \r\n                                               fontName:@&quot;Arial&quot;  \r\n                                               fontSize:30];\r\n\t\tlabel.position = &#x5B;CCDirector sharedDirector].screenCenter;\r\n\t\tlabel.color = ccCYAN;\r\n        &#x5B;self addChild:label];\r\n        \/\/ Second line of title\r\n \t\tCCLabelTTF* label2 = &#x5B;CCLabelTTF labelWithString:@&quot;Lesson 3&quot;\r\n                                                fontName:@&quot;Arial&quot;\r\n                                                fontSize:24];\r\n\t\tlabel2.color = ccCYAN;\r\n        label2.position = CGPointMake(&#x5B;CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);\r\n        &#x5B;self addChild:label2];\r\n        \/\/ Seed random number generator\r\n        srandom((UInt32)time(NULL));\r\n        \/\/ Initialize our moving target.\r\n        &#x5B;self initMovingTarget];\r\n        \/\/ Start animation -  the update method is called.\r\n        &#x5B;self scheduleUpdate];;\r\n\t}\r\n\treturn self;\r\n}\r\n-(void) dealloc\r\n{\r\n#ifndef KK_ARC_ENABLED\r\n\t&#x5B;super dealloc];\r\n#endif \/\/ KK_ARC_ENABLED\r\n}\r\n#pragma mark Player Movement\r\n-(void) acceleratePlayerWithX:(double)xAcceleration\r\n{\r\n    \/\/ Adjust velocity based on current accelerometer acceleration\r\n    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);\r\n    \/\/ Limit the maximum velocity of the player sprite, in both directions (positive &amp; negative values)\r\n    if (playerVelocity.x &gt; maxVelocity)\r\n    {\r\n        playerVelocity.x = maxVelocity;\r\n    }\r\n    else if (playerVelocity.x &lt; -maxVelocity)\r\n    {\r\n        playerVelocity.x = -maxVelocity;\r\n    }\r\n}\r\n#pragma mark update\r\n-(void) update:(ccTime)delta\r\n{\r\n    \/\/ Gain access to the user input devices \/ states\r\n    KKInput* input = &#x5B;KKInput sharedInput];\r\n    &#x5B;self acceleratePlayerWithX:input.acceleration.smoothedX];\r\n    \/\/ Accumulate up the playerVelocity to the player's position\r\n    CGPoint pos = player.position;\r\n    pos.x += playerVelocity.x;\r\n    \/\/ The player constrainted to inside the screen\r\n    CGSize screenSize = &#x5B;&#x5B;CCDirector sharedDirector] winSize];\r\n    \/\/ Half the player image size player sprite position is the center of the image\r\n    float imageWidthHalved = &#x5B;player texture].contentSize.width * 0.5f;\r\n    float leftBorderLimit = imageWidthHalved;\r\n    float rightBorderLimit = screenSize.width - imageWidthHalved;\r\n    \/\/ Hit left boundary\r\n    if (pos.x &lt; leftBorderLimit)\r\n    {\r\n        pos.x = leftBorderLimit;\r\n        \/\/ Set velocity to zero\r\n        playerVelocity = CGPointZero;\r\n    }\r\n    \/\/ Hit right boundary\r\n    else if (pos.x &gt; rightBorderLimit)\r\n    {\r\n        pos.x = rightBorderLimit;\r\n        \/\/ Set velocity to zero\r\n        playerVelocity = CGPointZero;\r\n    }\r\n    \/\/ Move the player\r\n    player.position = pos; \r\n}  \r\n#pragma mark MovingTarget\r\n\r\n-(void) initMovingTarget\r\n{\r\n    NSLog(@&quot;initMovingTarget&quot;);\r\n    \/\/ This is the image\r\n\tmovingTarget = &#x5B;CCSprite spriteWithFile:@&quot;red_ball.png&quot;];\r\n    \/\/ Add CCSprite for movingTarget\r\n    &#x5B;self addChild:movingTarget z:0 tag:2];\r\n    \/\/ Set the starting position and start movingTarget play sequence\r\n    &#x5B;self startMovingTargetSequence];\r\n    movingTargetMoveDuration = 4.0f;\r\n   \t\/\/ Unschedule the selector just in case. If it isn't scheduled it won't do anything.\r\n\t&#x5B;self unschedule:@selector(movingTargetUpdate:)];\r\n\t\/\/ Schedule the movingTarget update logic to run at the given interval.\r\n\t&#x5B;self schedule:@selector(movingTargetUpdate:) interval:0.1f];\r\n}\r\n\r\n-(void) startMovingTargetSequence\r\n{\r\n    NSLog(@&quot;startMovingTargetSequence&quot;);\r\n    \/\/ Get the window size\r\n    CGSize screenSize = &#x5B;&#x5B;CCDirector sharedDirector] winSize];\r\n    \/\/ Get the image size\r\n    CGSize imageSize = &#x5B;movingTarget texture].contentSize;\r\n    \/\/ Generate a random x starting position with offsets for center registration point.\r\n    int randomX = CCRANDOM_0_1() * (screenSize.width \/ imageSize.width);\r\n    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);\r\n    \/\/ Schedule the movingTarget update logic to run at the given interval.\r\n    &#x5B;self schedule:@selector(movingTargetUpdate:) interval:0.1f];\r\n}\r\n\r\n-(void) movingTargetUpdate:(ccTime)delta\r\n{\r\n    \/\/ CCSprite-&gt;CCNode no sequence of actions running.\r\n    if (&#x5B;movingTarget numberOfRunningActions] == 0)\r\n    {\r\n        NSLog(@&quot;movingTargetUpdate&quot;);\r\n        \/\/ Determine below screen position.\r\n        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( &#x5B;movingTarget texture].contentSize.height));\r\n        \/\/ CCAction to move a CCNode object to the position x,y based on position. \r\n        CCMoveTo* moveEnd = &#x5B;CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];\r\n        \/\/ Call back function for the action.\r\n        CCCallFuncN* callEndMovingTargetSequence = &#x5B;CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];\r\n        \/\/ Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.\r\n        CCSequence* sequence = &#x5B;CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];\r\n        \/\/ Run the sequence.\r\n        &#x5B;movingTarget runAction:sequence];\r\n    }\r\n}\r\n-(void) endMovingTargetSequence\r\n{\r\n    NSLog(@&quot;endMovingTargetSequence&quot;);\r\n    \/\/ Terminate running the moveTargetUpdate interval.\r\n    &#x5B;self unschedule:@selector(movingTargetUpdate:)];\r\n    \/\/ Set the starting position and start movingTarget play sequence\r\n    &#x5B;self startMovingTargetSequence];\r\n}\r\n\r\n@end\r\n<\/pre>\n<p>These methods are private and so we are declaring them in the implementation file. They are for controlling your moving target. We will talk more about them one at time.<\/p>\n<pre class=\"brush: objc; first-line: 8; highlight: [10,11,12,13,14]; title: ; notranslate\" title=\"\">\r\n#import &quot;GameLayer.h&quot;\r\n\r\n@interface GameLayer (PrivateMethods)\r\n-(void) initMovingTarget;\r\n-(void) movingTargetUpdate:(ccTime)delta;\r\n-(void) startMovingTargetSequence;\r\n-(void) endMovingTargetSequence;\r\n@end\r\n<\/pre>\n<p><strong>Step 5 &#8211; Integrate Moving Target into GameLayer.h File init method<\/strong><\/p>\n<p>To keep the eye clear which lesson you are viewing, change the subtitle on line 49.<\/p>\n<p>You have the initMovingTarget method to handle creating our moving target. Line 58 is added to call the initMovingTarget.<\/p>\n<p>You need to place the moving target at various horizontal positions on the top of the screen. We are using CCRANDOM_0_1() for the randomization. CCRANDOM_0_1() needs a one time seeding shown on line 56.<\/p>\n<pre class=\"brush: objc; first-line: 24; highlight: [49,55,56,57,58]; title: ; notranslate\" title=\"\">\r\n@implementation GameLayer\r\n\r\n-(id) init\r\n{\r\n\tif ((self = &#x5B;super init]))\r\n\t{\r\n        \/\/ Enable accelerometer input events.\r\n\t\t&#x5B;KKInput sharedInput].accelerometerActive = YES;\r\n\t\t&#x5B;KKInput sharedInput].acceleration.filteringFactor = 0.2f;\r\n        \/\/ Graphic for player\r\n        player = &#x5B;CCSprite spriteWithFile:@&quot;green_ball.png&quot;];\r\n\t\t&#x5B;self addChild:player z:0 tag:1];\r\n        \/\/ Position player        \r\n        CGSize screenSize = &#x5B;&#x5B;CCDirector sharedDirector] winSize];\r\n\t\tfloat imageHeight = &#x5B;player texture].contentSize.height;\r\n\t\tplayer.position = CGPointMake(screenSize.width \/ 2, imageHeight \/ 2);\r\n\t\tglClearColor(0.1f, 0.1f, 0.3f, 1.0f);\r\n\t\t\/\/ First line of title\r\n\t\tCCLabelTTF* label = &#x5B;CCLabelTTF labelWithString:@&quot;Kobold2d Intro Tutorial&quot; \r\n                                               fontName:@&quot;Arial&quot;  \r\n                                               fontSize:30];\r\n\t\tlabel.position = &#x5B;CCDirector sharedDirector].screenCenter;\r\n\t\tlabel.color = ccCYAN;\r\n        &#x5B;self addChild:label];\r\n        \/\/ Second line of title\r\n \t\tCCLabelTTF* label2 = &#x5B;CCLabelTTF labelWithString:@&quot;Lesson 3&quot;\r\n                                                fontName:@&quot;Arial&quot;\r\n                                                fontSize:24];\r\n\t\tlabel2.color = ccCYAN;\r\n        label2.position = CGPointMake(&#x5B;CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);\r\n        &#x5B;self addChild:label2];\r\n        \/\/ Seed random number generator\r\n        srandom((UInt32)time(NULL));\r\n        \/\/ Initialize our moving target.\r\n        &#x5B;self initMovingTarget];\r\n        \/\/ Start animation -  the update method is called.\r\n        &#x5B;self scheduleUpdate];;\r\n\t}\r\n\treturn self;\r\n}\r\n<\/pre>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\n<strong>Step 6 &#8211; Add the initMoving Target Method<\/strong><\/p>\n<p>You can see on line 123 the red_ball.png is the graphic image for the moving target. <\/p>\n<p>On line 125 the moving target is added. The z order is zero for this lesson. The tag value I mentioned in Lesson 1 as another way to get references to sprite objects. We are not using tags but since the game player has a tag value of 1, the moving target needed a different number. How about 2?<\/p>\n<p>One line 127 the startMovingTargetSequence method for the initial start position of the moving target is called.<\/p>\n<p>Line 128 sets the moving target moving duration value. For now the value never changes. But to add some variety to the game in a future lesson, we will decrease the value to speed up the moving target drop speed. The point is there needs to be a place to set the initial value.<\/p>\n<p>One line 130 a standard safety precaution cancels the movingTargetUpdate method from being called. This method gets the target moving and we will look at it in a bit. At this point it is not possible to call initiMovingTarget more than once. However later it might happen this initMovingTarget method is called more than once and we have stopped any sequence from running.<\/p>\n<p>Finally line 132 gets the moving target into motion. The movingTargetUpdate method defines that motion.<\/p>\n<pre class=\"brush: objc; first-line: 119; title: ; notranslate\" title=\"\">\r\n-(void) initMovingTarget\r\n{\r\n    NSLog(@&quot;initMovingTarget&quot;);\r\n    \/\/ This is the image\r\n\tmovingTarget = &#x5B;CCSprite spriteWithFile:@&quot;red_ball.png&quot;];\r\n    \/\/ Add CCSprite for movingTarget\r\n    &#x5B;self addChild:movingTarget z:0 tag:2];\r\n    \/\/ Set the starting position and start movingTarget play sequence\r\n    &#x5B;self startMovingTargetSequence];\r\n    movingTargetMoveDuration = 4.0f;\r\n   \t\/\/ Unschedule the selector just in case. If it isn't scheduled it won't do anything.\r\n\t&#x5B;self unschedule:@selector(movingTargetUpdate:)];\r\n\t\/\/ Schedule the movingTarget update logic to run at the given interval.\r\n\t&#x5B;self schedule:@selector(movingTargetUpdate:) interval:0.1f];\r\n}\r\n<\/pre>\n<p><strong>Step 7 &#8211; Add the startMovingTargetSequence Target Method<\/strong><br \/>\nThis method through line 144 provides the starting point for the moving target object.  <\/p>\n<p>Then on line 146, the movingTargetUpdate method is scheduled for call. That is where the animation sequence for the moving target is created.<\/p>\n<pre class=\"brush: objc; first-line: 135; title: ; notranslate\" title=\"\">\r\n-(void) startMovingTargetSequence\r\n{\r\n    NSLog(@&quot;startMovingTargetSequence&quot;);\r\n    \/\/ Get the window size\r\n    CGSize screenSize = &#x5B;&#x5B;CCDirector sharedDirector] winSize];\r\n    \/\/ Get the image size\r\n    CGSize imageSize = &#x5B;movingTarget texture].contentSize;\r\n    \/\/ Generate a random x starting position with offsets for center registration point.\r\n    int randomX = CCRANDOM_0_1() * (screenSize.width \/ imageSize.width);\r\n    movingTarget.position = CGPointMake(imageSize.width * randomX  + imageSize.width * 0.5f, screenSize.height + imageSize.height);\r\n    \/\/ Schedule the movingTarget update logic to run at the given interval.\r\n    &#x5B;self schedule:@selector(movingTargetUpdate:) interval:0.1f];\r\n}\r\n<\/pre>\n<p><strong>Step 8 &#8211; Add the movingTargetUpdate Target Method<\/strong><\/p>\n<p>The movingTargetIUpdate method creates two <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_action.html\" target = \"_blank\">CCAction<\/a> objects.<\/p>\n<p>The first is <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_move_to.html\" target = \"_blank\">CCMoveTo<\/a>  on line 158. This is the destination of the moving target. The current y position and the belowScreenPosition y are traversed over the movingTargetMoveDuration value.<\/p>\n<p>Line 160 creates the second <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_call_func_n.html\" target = \"_blank\">CCCallFuncN<\/a> to identify calling the endMovingTargetSequence method to handle the end of the animation.<\/p>\n<p>These two CCAction objects are then bundled on line 162 into a <a href=\"http:\/\/www.cocos2d-iphone.org\/api-ref\/2.0.0\/interface_c_c_sequence.html\" target = \"_blank\">CCSequence<\/a> CCAction. CCSequence is essentially an array. <\/p>\n<p>Line 164 runs the actions in the CCSequence.<\/p>\n<p>So the CCMoveTo CCAction is processed over the movingTargetMoveDuration and on its conclusion the CCCallFuncN CCAction invokes the endMovingTargetSequence method for cleanup. <\/p>\n<pre class=\"brush: objc; first-line: 149; title: ; notranslate\" title=\"\">\r\n-(void) movingTargetUpdate:(ccTime)delta\r\n{\r\n    \/\/ CCSprite-&gt;CCNode no sequence of actions running.\r\n    if (&#x5B;movingTarget numberOfRunningActions] == 0)\r\n    {\r\n        NSLog(@&quot;movingTargetUpdate&quot;);\r\n        \/\/ Determine below screen position.\r\n        CGPoint belowScreenPosition = CGPointMake(movingTarget.position.x, - ( &#x5B;movingTarget texture].contentSize.height));\r\n        \/\/ CCAction to move a CCNode object to the position x,y based on position. \r\n        CCMoveTo* moveEnd = &#x5B;CCMoveTo actionWithDuration:movingTargetMoveDuration position:belowScreenPosition];\r\n        \/\/ Call back function for the action.\r\n        CCCallFuncN* callEndMovingTargetSequence = &#x5B;CCCallFuncN actionWithTarget:self selector:@selector(endMovingTargetSequence)];\r\n        \/\/ Create a sequence, add the actions: the moveEnd CCMoveTo and the call back function for the end position.\r\n        CCSequence* sequence = &#x5B;CCSequence actions:moveEnd,callEndMovingTargetSequence, nil];\r\n        \/\/ Run the sequence.\r\n        &#x5B;movingTarget runAction:sequence];\r\n    }\r\n}\r\n<\/pre>\n<p>[ad name=&#8221;Google Adsense&#8221;]<br \/>\n<strong>Step 9 &#8211; Add the endMovingTargetSequence Target Method<\/strong><\/p>\n<p>This is the end of the moving target animation. The movingTargetUpdate method is removed as a scheduled method on line 171,<\/p>\n<p>Line 172 then sets up for the next moving target for a repeat performance.<\/p>\n<pre class=\"brush: objc; first-line: 167; title: ; notranslate\" title=\"\">\r\n-(void) endMovingTargetSequence\r\n{\r\n    NSLog(@&quot;endMovingTargetSequence&quot;);\r\n    \/\/ Terminate running the moveTargetUpdate interval.\r\n    &#x5B;self unschedule:@selector(movingTargetUpdate:)];\r\n    \/\/ Set the starting position and start movingTarget play sequence\r\n    &#x5B;self startMovingTargetSequence];\r\n}\r\n<\/pre>\n<p><!-- Place this tag where you want the +1 button to render --><br \/>\n<g:plusone annotation=\"inline\"><\/g:plusone><br \/>\n<a href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/19\/kobold2d-xcode-4-introduction-tutorial-lesson-2-set-landscape-orientation\/\">&lt;== Lesson 2<\/a>  || <a href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/21\/kobold2d-xcode-4-introduction-tutorial-lesson-4-progressively-increase-moving-target-speed\/\" >Lesson 4 ==&gt; <\/a>  <\/p>\n<div id=\"fb-root\"><\/div>\n<p><script src=\"https:\/\/connect.facebook.net\/en_US\/all.js#appId=105467682877384&amp;xfbml=1\"><\/script><fb:like href=\"https:\/\/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>\n<div id=\"fb-root\"><\/div>\n<p><script src=\"https:\/\/connect.facebook.net\/en_US\/all.js#xfbml=1\"><\/script><fb:comments href=\"https:\/\/www.lonhosford.com\/lonblog\/2011\/12\/18\/kobold2d-xcode-4-introduction-tutorial-lesson-1-basic-accelerometer\/\" num_posts=\"3\" width=\"500\"><\/fb:comments><\/p>\n<p><!-- Place this render call where appropriate --><br \/>\n<script type=\"text\/javascript\">\n  (function() {\n    var po = document.createElement('script'); po.type = 'text\/javascript'; po.async = true;\n    po.src = 'https:\/\/apis.google.com\/js\/plusone.js';\n    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);\n  })();\n<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&lt;== Lesson 2 || Lesson 4 ==&gt; We have not discussed much about the nature of the game. Believe me it is relatively routine. The green player will try to intercept a falling red target. The falling red target will start at random horizontal positions at the top of the screen and drop to the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[78,79,31,77,68],"class_list":["post-2673","post","type-post","status-publish","format-standard","hentry","category-general","tag-accelerometer","tag-cocos2d","tag-gaming","tag-kobold2d","tag-xcode"],"_links":{"self":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2673","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/comments?post=2673"}],"version-history":[{"count":43,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2673\/revisions"}],"predecessor-version":[{"id":3664,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/posts\/2673\/revisions\/3664"}],"wp:attachment":[{"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/media?parent=2673"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/categories?post=2673"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.lonhosford.com\/lonblog\/wp-json\/wp\/v2\/tags?post=2673"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}