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 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.
Lesson Downloads
- Game piece images for project
- IPhone images for project. Icons and splash screen.
- Completed Project. This is built in Kobold2d 1.0.1.
Step 1 – Build an Empty-Project Template
You can continue with the Lesson 4 project and make changes noted here. Otherwise the steps for creating this project from an Empty-Project template are the same as Lesson 1 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.
[ad name=”Google Adsense”]
Step 2 – Set Properties in config.lua
There are no new configuration properties from Lesson 4. Complete config.lua file is included here for your copy convenience.
--[[ * 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 = "GameLayer", -- 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 & Autorotation DeviceOrientation = DeviceOrientation.LandscapeLeft, AutorotationType = Autorotation.None, ShouldAutorotateToLandscapeOrientations = NO, ShouldAutorotateToPortraitOrientations = NO, AllowAutorotateOnFirstAndSecondGenerationDevices = NO, -- Ad setup EnableAdBanner = NO, PlaceBannerOnBottom = YES, LoadOnlyPortraitBanners = NO, LoadOnlyLandscapeBanners = NO, AdProviders = "iAd, AdMob", -- comma seperated list -> "iAd, AdMob" means: use iAd if available, otherwise AdMob AdMobRefreshRate = 15, AdMobFirstAdDelay = 5, AdMobPublisherID = "YOUR_ADMOB_PUBLISHER_ID", -- 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
Step 3 – GameLayer.h
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.
Line 17 tracks the number of times the moving target and the player collided.
/* * Kobold2D™ --- http://www.kobold2d.org * * Copyright (c) 2010-2011 Steffen Itterheim. * Released under MIT License in Germany (LICENSE-Kobold2D.txt). */ #import "kobold2d.h" @interface GameLayer : CCLayer { CCSprite* player; CGPoint playerVelocity; CCSprite* movingTarget; float movingTargetMoveDuration; int totalAttempts; int totalHits; } @end
Step 4 – Add checkForCollision Private Method
Complete GameLayer.m file is included here for your copy convenience. I will focus on the code changes to accommodate the collision detection.
/* * Kobold2D™ --- http://www.kobold2d.org * * Copyright (c) 2010-2011 Steffen Itterheim. * Released under MIT License in Germany (LICENSE-Kobold2D.txt). */ #import "GameLayer.h" @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:@"green_ball.png"]; [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:@"Kobold2d Intro Tutorial" fontName:@"Arial" fontSize:30]; label.position = [CCDirector sharedDirector].screenCenter; label.color = ccCYAN; [self addChild:label]; // Second line of title CCLabelTTF* label2 = [CCLabelTTF labelWithString:@"Lesson 5" fontName:@"Arial" 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 & negative values) if (playerVelocity.x > maxVelocity) { playerVelocity.x = maxVelocity; } else if (playerVelocity.x < -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 < leftBorderLimit) { pos.x = leftBorderLimit; // Set velocity to zero playerVelocity = CGPointZero; } // Hit right boundary else if (pos.x > 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(@"initMovingTarget"); // This is the image movingTarget = [CCSprite spriteWithFile:@"red_ball.png"]; // 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(@"startMovingTargetSequence"); // 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->CCNode no sequence of actions running. if ([movingTarget numberOfRunningActions] == 0) { NSLog(@"movingTargetUpdate"); // 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(@"endMovingTargetSequence"); [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 < 2.0f) { movingTargetMoveDuration = 2.0f; } NSLog(@"movingTargetMoveDuration: %f",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 < maxCollisionDistance) { totalHits++; NSLog(@"HIT! Total attempts: %i. Total hits: %i", totalAttempts, totalHits); [self endMovingTargetSequence]; } } @end
First set of changes are in the declaration of a new private method checkForCollision.
#import "GameLayer.h" @interface GameLayer (PrivateMethods) -(void) initMovingTarget; -(void) movingTargetUpdate:(ccTime)delta; -(void) startMovingTargetSequence; -(void) endMovingTargetSequence; -(void) checkForCollision; @end
[ad name=”Google Adsense”]
Step 5 – Initialize Scoring Properties and Update Subtitle
The scoring properties are initialized on lines 35 and 37.
Line 54 clarifies the lesson in the subtitle.
-(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:@"green_ball.png"]; [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:@"Kobold2d Intro Tutorial" fontName:@"Arial" fontSize:30]; label.position = [CCDirector sharedDirector].screenCenter; label.color = ccCYAN; [self addChild:label]; // Second line of title CCLabelTTF* label2 = [CCLabelTTF labelWithString:@"Lesson 5" fontName:@"Arial" 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; }
Step 6 – Call the Collision Detection Method
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.
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.
#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 < leftBorderLimit) { pos.x = leftBorderLimit; // Set velocity to zero playerVelocity = CGPointZero; } // Hit right boundary else if (pos.x > rightBorderLimit) { pos.x = rightBorderLimit; // Set velocity to zero playerVelocity = CGPointZero; } // Move the player player.position = pos; // Collision check [self checkForCollision]; }
Step 7 – Kill The Moving Target Actions
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.
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.
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.
The solution is to add the stopAllActions 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.
-(void) endMovingTargetSequence { NSLog(@"endMovingTargetSequence"); [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 < 2.0f) { movingTargetMoveDuration = 2.0f; } NSLog(@"movingTargetMoveDuration: %f",movingTargetMoveDuration); // Set the starting position and start movingTarget play sequence [self startMovingTargetSequence]; }
Step 8 – Count the Total Moving Targets
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.
-(void) startMovingTargetSequence { NSLog(@"startMovingTargetSequence"); // 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]; }
[ad name=”Google Adsense”]
Step 9 – Add Collision Detection Method
The checkForCollision method is our new method that handles collisions between the moving target and the player.
The process is twofold. One to compute the distance that defines a collision. Lines 196 – 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.
Second part of the collision detection process is computing the actual dist and and line 205 does that for us.
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.
#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 < maxCollisionDistance) { totalHits++; NSLog(@"HIT! Total attempts: %i. Total hits: %i", totalAttempts, totalHits); [self endMovingTargetSequence]; } }
[ad name=”Google Adsense”]