Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X
Articles

Simple Cocos2D Collision Detection

I’m currently developing an iPhone game (watch this space…) and required a very simple collision detection system. My application is pretty simple and doesn’t require any complex collision engines included in the likes of Chipmunk or Box2d, however, after trawling around the internet for a good few hours looking for a way to do it with the basic cocos2d framework, I decided to write my own method.

My example involves two sprites, Player and Platform. In this scenario, I want to detect when the Player object intersects the Platform object. The problem is, CCSprite does not create the Rect required to run the method CGRectIntersectsRect(rect,rect). So to get around this, we must write our own method. I called mine getBounds.

First of all, we need to extend the CCSprite type to add on the additional method. Add a new class which inherits CCSprite:

I named mine “Player”. All we want to do at this point is add 1 line of code to the .h file:

#import
#import “cocos2d.h”

@interface Player : CCSprite {}

// this is the line we’re after
-(CGRect) getBounds;

@end

After saving that file, head on over to the implementation file for the “Player” class, the .m file, and define what your new getBounds method should actually do. Beneath the @implementation line, add the following method:

(CGRect) getBounds {
CGSize s = [self contentSize];
s.width *= scaleX_;
s.height *= scaleY_;
return CGRectMake(
position_.x – s.width * anchorPoint_.x,
position_.y – s.height * anchorPoint_.y,
s.width,
s.height);
}

What this snippet of code is doing is quite simple. On the first line of the method, we are creating a new CGSize object, which we are setting as the contentSize property of the object. The next few lines are defining the width and height of the object, based on properties of contentSize. The real meat of the function begins when we make the rect:
return CGRectMake(
position_.x – s.width * anchorPoint_.x,
position_.y – s.height * anchorPoint_.y,
s.width,
s.height);

What’s happening here is the x and y coordinates and the width and height of the object are being set which is returning a rect, usable in any future intersection methods. With the method in place, the final step is to implement it into your intersection code:
CGRect playerRect = [player getBounds];
CGRect platformRect = [platform getBounds];
if(CGRectIntersectsRect(playerRect,platformRect)) {
// do your stuff
}

As you can see, in this section of code, within the main game loop, I am creating two rects on the fly using the newly created method and using that to make a simple but useful collision detection test.

No related posts.

  • nice one man

    ZaldzBugz

    December 15, 2010

  • hope it helped :)

    Andy G

    January 5, 2011

  • OK, I wrote everything like you said, but I keep getting two errors, these 2 lines:
    CGRect mouseRect = [mouse getBounds];
    CGRect dogRect = [dog getBounds];

    For each line the debugger says:
    ‘CCSprite’ may not respond to ‘-getBounds’
    (Messages without a matching method signature will be assumed to return ‘id’ and accept ‘…’ as arguments.)

    And:

    Invalid initializer

    Who made the error? Me or you? Because I think I did everything right, and my sprites are initialized and everything..

    Can you help me?

    Thanks

    M.Mac

    January 26, 2011

  • Have you declared getBounds in your new class’s header file. It should look something like:
    “-(void) getBounds”

    That means the method is properly declared and hopefully will be stop the errors throwing!

    Let me know how you get on with this :)

    Andy G

    January 27, 2011

  • I did declare getBounds and I triple-checked my code for typos and copy-pasted yours (and changed the sprite names) and I still received the same error:

    Invalid initializer

    And player.m is importing player.h.
    And gamescene.m is importing player.h

    Though, I found a “dirty” way to make it work, but I think this way of doing it would give me a lot of trouble if i decide to use a lot of sprites:

    CGRect mouseRect = CGRectMake(mouse.position.x, mouse.position.y, mouse.contentSize.width, mouse.contentSize.width);
    CGRect dogRect = CGRectMake(dog.position.x, dog.position.y, dog.contentSize.width, dog.contentSize.width);
    if(CGRectIntersectsRect(mouseRect,dogRect)) {
    [[CCDirector sharedDirector] replaceScene:[GameOver scene]];
    }

    This method works, but requires a lot (relatively) of coding for each sprite.

    I will now try to implement my technique in the getBounds method.

    But I still get the errors.

    Oh, and in the second code snippet in your tutorial, I think you forgot to add an – before (CGRect), I did “correct” this in my project because it gave me an error if I removed the -. Do you think it is the cause of my issue?

    Thank you

    M.Mac

    January 28, 2011

  • Just discovered I could use a built-in cocos2d method: boundingBox

    So my whole collision detection code is:
    CGRect mouseRect = [mouse boundingBox];
    CGRect dogRect = [dog boundingBox];

    if (CGRectIntersectsRect(mouseRect, dogRect)) {
    //[fichiersToDelete addObject:fichier];
    NSLog(@”Touché”);
    }

    But in my case, many dogs are appearing and are in an NSMutableArray and I can’t make my dog_ array work with this method. What am I forgetting?

    (And I am declaring my NSMutableArray with this in my header: NSMutableArray *dog_; )

    M.Mac

    January 28, 2011

  • [...] This post was mentioned on Twitter by andygirvan, hyperipod. hyperipod said: @andygirvan Answered: http://bit.ly/icVOMb [...]

Leave a comment  

name*

email*

website

Submit comment