我是否需要取消计划我的tick方法?

时间:2013-09-04 03:58:53

标签: cocos2d-iphone box2d collision-detection

我正在尝试模拟cocos2d中的轻弹,我需要在每次用户触摸结束时创建一个球,但是我无法在tick方法中移动球,我无法摧毁之后,球(这是一个b2体)没有安排方法。

- (void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    touch = [touches anyObject];
    location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];

    endPoint = location;
    force = b2Vec2(endPoint.x - startPoint.x ,endPoint.y - startPoint.y);

    if ((force.x != 0) || (force.y != 0)) {
        if (ballCount == 0) {
            ball.position = startPoint;
            [self createBall]; - Here i create the ball every time
            [self schedule: @selector(tick:)]; -I schedule the tick method right after the ball is created
            [self scheduleOnce:@selector(kick) delay:0]; - This is the only place the ball will launch. For some reason I can't get the kick method to work any where else
        }
    }

- (void)kick
{
    int speed = 30;
    float32 setSpeed = speed/sqrt(powf(force.x,2) + powf(force.y, 2));

    b2Vec2 ballSpeed = b2Vec2(force.x * setSpeed, force.y * setSpeed);
    _ballBody->SetLinearVelocity(ballSpeed);
}

- (void)tick:(ccTime) dt {
    _world->Step(dt, 10, 10);
    ballData = (__bridge CCSprite *)_ballBody->GetUserData();

    ballData.position = ccp(_ballBody->GetPosition().x * PTM_RATIO,
                        _ballBody->GetPosition().y * PTM_RATIO);
    ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(_ballBody->GetAngle());

    std::set<b2Body *>toDestroy;

    //takes collisions from contact listener
    std::vector<MyContact>::iterator pos;
    for(pos = _contactListener->_contacts.begin();
        pos != _contactListener->_contacts.end(); ++pos) {
        MyContact contact = *pos;
        bodyA = contact.fixtureA->GetBody();
        bodyB = contact.fixtureB->GetBody();
        if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
            spriteA = (__bridge CCSprite *) bodyA->GetUserData();
            spriteB = (__bridge CCSprite *) bodyB->GetUserData();
            contactPositionX = spriteA.position.x;
            contactPositionY = spriteB.position.y;
            if (spriteA.tag == kCurrentItem && spriteB.tag == 8)
            {
                NSLog(@"contact");
                [self removeChild:spriteA cleanup:YES];
                [self removeChild:spriteB cleanup:YES];
                toDestroy.insert(bodyA);
                toDestroy.insert(bodyB);
                [self unschedule:@selector(tick:)]; (i unschedule the tick method every time which in turn messes up my other sprites.)
            }
        }
    }

    for(std::set<b2Body *>::iterator pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2)
    {
        b2Body *body = *pos2;
        _world->DestroyBody(body);
    }
    toDestroy.clear();
}

0 个答案:

没有答案