我正在尝试用Cocos2d和花栗鼠(通过SpaceManager)创建一个软球,用一堆矩形链在一起,然后用弹簧连接到一个中心体。
Something like these examples
但为了做到这一点,我想我需要在创建完所有cpshape之后将它们存储在一个数组中,这样我就可以通过数组循环,用约束将它们链接在一起。
然而,当我尝试将cpshape放入数组时,我得到一个错误,告诉我这是一个“不兼容的指针类型”。所以。。。我要么需要使用数组以外的东西(我试过一个集合,它也不起作用),要么我需要对形状做些什么使它兼容。。。但是什么?或者我需要另一个办法。
有什么想法吗?
- (id) init { if ( (self = [super init]) ) { SpaceManager * spaceMgr = [[SpaceManager alloc] init]; [spaceMgr addWindowContainmentWithFriction:1.0 elasticity:1.0 inset:cpv(5, 5)]; // This is a layer that draws all the chipmunk shapes ChipmunkDrawingLayer *debug = [[ChipmunkDrawingLayer node] initWithSpace:spaceMgr.space]; [self addChild:debug]; int ballPeices = 10; // the number of peices I want my ball to be composed of int ballRadius = 100; float circum = M_PI * (ballRadius * 2); float peiceSize = circum / ballPeices; float angleIncrement = 360 / ballPeices; CGPoint origin = ccp(240, 160); float currentAngleIncrement = 0; NSMutableArray *peiceArray = [NSMutableArray arrayWithCapacity:ballPeices]; for (int i = 0; i < ballPeices; i++) { float angleIncrementInRadians = CC_DEGREES_TO_RADIANS(currentAngleIncrement); float xp = origin.x + ballRadius * cos(angleIncrementInRadians); float yp = origin.y + ballRadius * sin(angleIncrementInRadians); // This is wrong, I need to figure out what's going on here. float peiceRotation = atan2( origin.y - yp, origin.x - xp); cpShape *currentPeice = [spaceMgr addRectAt:ccp(xp, yp) mass:1 width:peiceSize height:10 rotation:peiceRotation]; currentAngleIncrement += angleIncrement; [peiceArray addObject:currentPeice]; //!! incompatible pointer type } spaceMgr.constantDt = 0.9/55.0; spaceMgr.gravity = ccp(0,-980); spaceMgr.damping = 1.0; } return self; }
不兼容的指针类型很容易解释:)
[NSMutableArray addObject] 定义如下:
[NSMutableArray addObject]
- (void)addObject:(id)anObject
那么什么是 id 然后呢?好问题!记住,Objective-C仍然是C的核心。根据 Objective-C Programming Guide
id
typedef struct objc_object { Class isa; } *id;
太好了,现在我们知道 *id 但那你呢 它自己?这就是方法签名中引用的内容。为此,我们必须考虑 objc.h
*id
typedef id (*IMP)(id, SEL, ...);
cpSpace* 不适合,所以如果您尝试将它们放入 NSMutableArray 使用那个信息。
cpSpace*
NSMutableArray