Cocos2d - How to check for Intersection between ob

2019-04-15 16:39发布

I'm currently developing a doodle-jump style game in Cocos2d for iPhone and have a scene set up with two different layers - game objects (platforms, collectables etc...) and player (character, controlled by the player).

I have these in separate layers because I want to scroll the entire game objects layer down when the player jumps up - giving it the vertical, doodle-jump style feel.

The problem is that intersection between the player and the platforms doesn't occur because they're on different layers.

Does anyone know how this can be solved? Some have mentioned convertToWorldCoords but I'm lost with that!

1条回答
老娘就宠你
2楼-- · 2019-04-15 17:02

Yessir, convertToWorldCoords! Or, something like that -- basically you want to have an understanding of your player and game-object positions in relation to each other, and one way to do that is to transform them all to the "world" coordinates. Alternately you could transform the player position/rectangle to be in your game-objects' coordinate system.

Want to keep it simple with just some CGRect intersection tests? Extend CCNode with a category:

CCNode+CoordHelpers.h

#import "CCNode.h"

@interface CCNode (CoordHelpers)
- (CGRect) worldBoundingBox;
@end

CCNode+CoordHelpers.m

#import "CCNode+CoordHelpers.h"

@implementation CCNode (CoordHelpers)
-(CGRect)worldBoundingBox {
    CGRect rect = CGRectMake(0, 0, contentSize_.width, contentSize_.height);
    return CGRectApplyAffineTransform(rect, [self nodeToWorldTransform]);
}
@end

Then, for super simple CGRect collision testing:

if(CGRectIntersectsRect([playerObj worldBoundingBox], [otherObj worldBoundingBox])    
{/*...do stuff...*/}

Make sure to #import "CCNode+CoordHelpers.h" wherever you need to use this method!

查看更多
登录 后发表回答