在box2d中为精灵设定恒定和递增的速度

Setting constant and increasing speed for sprite in box2d

本文关键字:速度 精灵 box2d      更新时间:2023-10-16

我试图为我正在开发的游戏创造3个不同的难度等级(简单,中等和困难)。我使用一个标志来区分3(简单= 1,中等= 2,困难= 3)。现在,我试图弄清楚如何将速度设置为常量,然后在20次碰撞后增加它,而中等,然后在10次碰撞后增加,当选择困难时。这是我如何尝试实现它:

-(id)init)
{vel = 8;
counter = 0;}
-(void)update:(ccTime)dt{
_world->Step(dt, vel, 10);
    for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
        if (b->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *)b->GetUserData();
            sprite.position = ccp(b->GetPosition().x * PTM_RATIO,
                              b->GetPosition().y * PTM_RATIO);
            sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
        }
    }
    if((contact.fixtureA == _paddleFixture && contact.fixtureB == _ballFixture) || (contact.fixtureA == _ballFixture && contact.fixtureB == _paddleFixture))
    {
        counter++;
        [self updateSpeed];
    }
}
-(void)updateSpeed{
if(diffLevel == 2)
{
    if(counter%20 == 0)
    {
        vel = vel + 5;
    }
}
else if(diffLevel == 3)
{
    if(counter%10 == 0)
    {
        vel = vel + 10;
    }
}
else
{
    vel = 8;
}}

计数器确实工作,但每当计数器被20或10整除时,速度似乎不会增加,而且我也无法获得简单级别的恒定速度。一开始非常快,然后逐渐慢下来。我哪里做错了?请帮助。

有人建议我这样做,它很有效,所以我就把它贴出来,以防其他人需要它:

- (void)update:(ccTime) dt {
    _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)
            {
                int maxSpeed = 140;
                b2Vec2 dir = b->GetLinearVelocity();
                dir.Normalize();
                float currentSpeed = dir.Length();
                float accelerate = vel;
                if(currentSpeed < maxSpeed)
                {
                    b->SetLinearVelocity(accelerate * dir);
                }
                sprite.position = ccp(b->GetPosition().x * PTM_RATIO,
                                      b->GetPosition().y * PTM_RATIO);
                sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}}}

这基本上是我唯一修改的代码部分。我让updatesspeed方法进行计算,以增加和设置球的最大速度