Cocos2d - How to check for Intersection between objects in different layers

自古美人都是妖i 提交于 2019-12-04 19:46:51

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!