0

再会 !我使用物理引擎“花栗鼠”。尝试通过单击创建动态对象。AddBalls() 创建所需的身体和形状。通过单击它必须生成一个新对象并将其放入数组中。

-(void)AddBalls: (UIImageView *)image;
{
    cpBody *ball2Body = cpBodyNew(100.0, INFINITY);
    ball2Body->p = cpv(60, 250);
    cpSpaceAddBody(space, ball2Body);

    cpShape *ball2Shape = cpCircleShapeNew(ball2Body, 20.0, cpvzero);
    ball2Shape->e = 0.5;
    ball2Shape->u=0.2;
    ball2Shape->data = (__bridge void*)image;
    ball2Shape->collision_type = 1;
    cpSpaceAddShape(space, ball2Shape);

    [children addObject: (__bridge id)ball2Shape];//EXC_BAD_ACCESS code=1
}

-(void)setupChipmunk

{
    cpInitChipmunk();
    space = cpSpaceNew();
    space->gravity = cpv(0, -100);
    space->elasticIterations = 10;

    [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(tick:) userInfo:nil repeats:YES];

    cpBody *ballBody = cpBodyNew(100.0, INFINITY);
    ballBody->p = cpv(60,250);
    cpSpaceAddBody(space, ballBody);
    cpShape *ballShape = cpCircleShapeNew(ballBody, 20.0, cpvzero);
    ballShape->e = 0.5;
    ballShape->u = 0.8;
    (ballShape->data) =(__bridge void*) ball;
    ballShape->collision_type = 1;
    cpSpaceAddShape(space, ballShape);
}

-(void)tick:(NSTimer *)timer
{
    cpSpaceStep(space, 1.0f/60.0f);
    cpSpaceHashEach(space->activeShapes, &updateShape, nil);
}

-(void) updateShape (void *ptr, void *unused)
{
    cpShape *shape = (cpShape*)ptr;

    if(shape == nil || shape->body == nil || shape->data == nil) {
        NSLog(@"Unexpected shape please debug here...");
        return;
    }

    if([(__bridge UIImageView*)shape->data isKindOfClass:[UIView class]]) {
        [(UIView *)((__bridge UIImageView*)shape->data) setCenter:CGPointMake(shape->body->p.x, 480 - shape->body->p.y)];
    }
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (void)handleTap:(UITapGestureRecognizer *)sender {     
    if (sender.state == UIGestureRecognizerStateEnded) {
        [self AddBalls];
    }
}

方法 AddBalls 应该将新形状放入数组中。但我得到了错误“ EXC_BAD_ACCESS...”。我应该怎么办?谢谢

4

1 回答 1

2

您不能将任何类型强制转换为id,它实际上必须是 Objective-C 类型。您需要ball2ShapeNSValue.

[children addObject:[NSValue value:&ball2Shape withObjCType:@encode(cpBody*)]];

...
//When you need to use/free the values
for (NSValue *value in children)
{
    cpBody *body = (cpBody*)[value pointerValue];

    //Use body like you did above.

    //Even though it is ARC you will need to free cpBody since
    // it is not an Objective-C object
    cpBodyFree(body);
}
于 2012-11-19T13:48:37.763 回答