0

我正在尝试在 cocos2d 中模拟轻弹,每次用户触摸结束时我都需要创建一个球,但是在 tick 方法期间我无法让球移动,也无法销毁球(是 b2body) 之后,无需每次都取消计划该方法。

- (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();
}
4

0 回答 0