Box2D getPosotion错误线程1:EXC_BAD_ACCESS iPhone

时间:2013-06-25 13:17:22

标签: ios objective-c xcode cocos2d-iphone box2d-iphone

我正在开发一款游戏。我在box2d面临问题。 我创建了一个World和一个Web(精灵,正文),然后我在touchend上投掷web,以及一个获取精灵位置及其给出错误的刻度选择器。

这是勾选者 enter image description here

onTouchEnd

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

    if (freeBody) {
        [self schedule: @selector(tick:)];
        [self schedule:@selector(WebHitsFood:) interval:0.01f];

        freeBody->SetType(b2_dynamicBody);

        //this is the maximum force that can be applied
        const CGFloat maxForce = 600;


        //get the location of the end point of the swipe
        UITouch *myTouch = [touches anyObject];
        CGPoint location = [myTouch locationInView:[myTouch view]];
        location = [[CCDirector sharedDirector] convertToGL:location];


        //get the rotation b/w the start point and the end point
        CGFloat rotAngle = atan2f(location.y - startPoint.y,location.x - startPoint.x);

        //the distance of the swipe if the force
        CGFloat distance = ccpDistance(startPoint, location) * 0.5;

        //put a cap on the force, too much of it will break the rope
        if (distance>maxForce) distance = maxForce;

        //apply force
        freeBody->ApplyForce(b2Vec2(cosf(rotAngle) * distance, sinf(rotAngle) * distance), freeBody->GetPosition());

        //lose the weak reference to the body for next time usage.
        freeBody = nil;


    }
    self.isTouchEnabled = NO;

}

和创建Web方法

-(void) createWeb
{
    freeBodySprite = [CCSprite spriteWithFile:@"web1.png"];//web_ani_6_1
    //freeBodySprite.position = ccp(100, 300);
    [self addChild:freeBodySprite z:2 tag:6];

    CGPoint startPos = CGPointMake(100, 320/1.25);

    bodyDef.type = b2_staticBody;
    bodyDef.position = [self toMeters:startPos];
    bodyDef.userData = freeBodySprite;


    float radiusInMeters = ((freeBodySprite.contentSize.width * freeBodySprite.scale/PTM_RATIO) * 0.5f);
    shape.m_radius = radiusInMeters;


    fixtureDef.shape = &shape;
    fixtureDef.density = 0.5f;
    fixtureDef.friction = 1.0f;
    fixtureDef.restitution = 0.0f;

    circularObstacleBody = world->CreateBody(&bodyDef);
    stoneFixture = circularObstacleBody->CreateFixture(&fixtureDef);
    freeBody = circularObstacleBody;

}

2 个答案:

答案 0 :(得分:0)

你确定GetPosition()是问题吗?尝试添加行

float test = b-> GetPosition()。x;

就在问题出现之前,确定问题是否实际上与GetPosition()有关,或者是否是作为exc_bad_access源的myActor.position。

答案 1 :(得分:0)

修复崩溃的简便方法:

for(b2Body* b= world->GetBodyList(); b; B->GetNext())
{
    id sprite = b->GetUserData();

   if( sprite && [sprite isKindOfClass:[CCSprite class])
   {
         CCSprite *myActor = (CCSprite*) sprite;

         myActor.position = CGPointMake(b->getPosition().x*PTM_RATIO, b->getPosition().y*PTM_RATIO);

       myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
   }
}