如何在cocos2d中沿着圆弧路径旋转物理或动态体(box2D)

时间:2012-12-03 07:48:23

标签: cocos2d-iphone rotation box2d-iphone bezier

当我是cocoa2d的新手时,我正在努力沿着弧形路径旋转物理或动态体。

我尝试的方式如下:

#define COS_ANIMATOR(position, timeCount, speed, waveMagnitude) ((cosf(timeCount * speed) * waveMagnitude) + position)

#define SIN_ANIMATOR(position, timeCount, speed, waveMagnitude) ((sinf(timeCount * speed) * waveMagnitude) + position)

CCSpriteBatchNode *pipe_parent = [CCSpriteBatchNode batchNodeWithFile:@"pipe.png" capacity:100];
        CCTexture2D *pipeSpriteTexture_ = [pipe_parent texture];

        PhysicsSprite *pipeSprite = [PhysicsSprite spriteWithTexture:pipeSpriteTexture_ rect:CGRectMake(0 ,0 ,55,122)];

        //pipe = [CCSprite spriteWithFile:@"pipe.png" 
                                              // rect:CGRectMake(0, 0, 55, 122)];

        [self addChild:pipeSprite];
        // pipe.position = ccp(s.width/2 , 420.0);


        b2BodyDef myBodyDef;
        myBodyDef.type = b2_staticBody; //this will be a dynamic body
        myBodyDef.position.Set(((s.width/2) - 90)/PTM_RATIO, 420.0/PTM_RATIO); //set the starting position
        myBodyDef.angle = 0; //set the starting angle

        b2Body* staticBody = world->CreateBody(&myBodyDef);


        b2PolygonShape boxShape;
        boxShape.SetAsBox(1,1);

        b2FixtureDef boxFixtureDef;
        boxFixtureDef.shape = &boxShape;
        boxFixtureDef.density = 1;
        boxFixtureDef.userData = pipeSprite;
        boxFixtureDef.filter.groupIndex = -1;
        staticBody->CreateFixture(&boxFixtureDef);
        [pipeSprite setPhysicsBody:staticBody];

-(void) draw
{
    //
    // IMPORTANT:
    // This is only for debug purposes
    // It is recommend to disable it
    //
    [super draw];


    const CGPoint newSpritePosition = ccp(COS_ANIMATOR(150, mTimeCounter, 0.05,50), SIN_ANIMATOR(400, mTimeCounter, -0.05, 50));

    pipeSprite.position = newSpritePosition;

    ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );

    kmGLPushMatrix();

    world->DrawDebugData(); 

    kmGLPopMatrix();
}

按照这种方法,我的精灵以圆周运动旋转而不是在弧形路径中旋转。

请提出您的想法或建议。

全部谢谢

1 个答案:

答案 0 :(得分:0)

当你谈到在弧形路径中旋转时,我并不完全确定你想要完成的是什么。我只看到你设置一个位置,而不是一个旋转,所以你只是想设置一个位置,或一个旋转,或两者兼而有之?您的位置代码看起来像是在尝试获得圆形(或椭圆形)路径,因为您在x,y位置使用正弦和余弦。

如果你想沿着正弦曲线移动一个精灵,我今天就这样做了,它需要一些试验和错误。我有一些幅度和周期的变量,从那里我在精灵的更新中找出了一个很好的正弦曲线运动:方法。

CGPoint initialPosition; // set this to the sprite's initial position
float amplitude; // in points
float period; // in points
float y, x = initialPosition.x;
-(void) update:(ccTime)dt
{
   x += dt * 100; // speed of movement across the screen.  Picked by trial and error.
   y = initalPosition.y + amplitude * sinf((x - initialPosition.x)/period);
   sprite.position = ccp(x,y);
   sprite.rotation = cosf((x - initialPosition.x)/period); // optional if you want to rotate along the path as well
}

不知道这是否是您正在寻找的任何东西,但它可能会给您一些想法。