Reputation:
[I have 2 objects, both of them subclass of CCSprite. Each one of them has a CCSprite variable that actually represents the sprite image
Example:
@interface Player : CCSprite
{
CCSprite *sprite;
}
@property (nonatomic, retain) CCSprite *sprite;
I'm trying to detect collision of the both but when I try:
- (void)detectCollision:(id)sender
{
for (Player *tempPlayer in self.playersArray) {
if (CGRectIntersectsRect([tempPlayer boundingBox], [mainPlayer boundingBox])) {
//Collision
}
}
}
It doesn't recognize any collision, when I try:
- (void)detectCollision:(id)sender
{
for (Player *tempPlayer in self.playersArray) {
if (CGRectIntersectsRect([tempPlayer.sprite boundingBox], [mainPlayer.sprite boundingBox])) {
//Collision
}
}
}
It detects collision when both objects are displayed on screen even if the haven't collided yet.
Edit: Forgot to add boundingBox to the objects...
Thanks
Upvotes: 1
Views: 502
Reputation: 3045
I never use bounding boxes. You may have to do some math and figure out the length/height of your objects in pixels and work with that. Also, if you have any anchorpoints set, this could throw off everything and your collision won't work.
To implement your own collision function/thing, you could do it inside your time function (probably ccTime if you are using cocos2d) and work with their CGPoints (positions)
Thats what I would do personally, but most people use chipmunk for iphone programming.
Upvotes: 0
Reputation: 2368
tempPlayer.sprite and mainPlayer.sprite bounding boxes will represent the rect in their own superview which is also a sprite, not the world. For example if the mainPlayer's rect is (150, 200, 100, 100), and the sprite inside it has the same rect, its boundingBox will be (0, 0, 100, 100).
I once got this problem and solved it as follows: x for tempPlayer.sprite in world coordinates = x for tempPlayer + x for tempPlayer.sprite.
and same thing for y.
Upvotes: 1
Reputation: 4276
Have you looked at the reference information for CGRectIntersectCGRect ?
You will note that it requires to be passed two CGRect structures. You are passing a Player object in the first code you posted and a CCSprite in the second.
Upvotes: 1