使精灵在box2d中以一个角度反弹

时间:2013-03-06 05:56:19

标签: c++ cocos2d-iphone box2d

在我想要制作的游戏中,我有一个球形精灵,由于box2d而反弹。以下是我当前代码的外观:

-(id)init
{
    ball = [CCSprite spriteWithFile:@"ball.png"];
    ball.position = ccp(150, winSize.height * 0.78);
    [self addChild:ball];
    ball.tag = 2;

b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(150/PTM_RATIO, 450/PTM_RATIO);
ballBodyDef.userData = ball;
_body = _world->CreateBody(&ballBodyDef);

b2CircleShape circle;
circle.m_radius = 26.0/PTM_RATIO;

b2FixtureDef ballShapeDef;
ballShapeDef.shape = &circle;
ballShapeDef.density = 0.5f;
ballShapeDef.friction = 1.0f;
ballShapeDef.restitution = 1.0f;
_ballFixture = _body->CreateFixture(&ballShapeDef);

b2Vec2 force = b2Vec2(160, 375);
_body->ApplyLinearImpulse(force, ballBodyDef.position);}

- (void)update:(ccTime) dt {
if(_isPaused == FALSE)
{
    _world->Step(dt, 10, 10);
    for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
        if (b->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *)b->GetUserData();
            if(sprite.tag == 2)
            {
                sprite.position = ccp(b->GetPosition().x * PTM_RATIO,
                              b->GetPosition().y * PTM_RATIO);
                sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
            }
        }
    }}

弹跳本身很好,我的问题是有些情况下球会在直线上反弹,可以说是垂直或水平连续,我试图避免。所以我的问题是,如何让我的球精灵以一个角度而不是一条直线反弹,这样它就不会被卡在同一个方向上无限弹跳?

1 个答案:

答案 0 :(得分:0)

您可以“随机”或以相等的间隔对身体或世界施加微小的力或重力变化。