2012-12-03 39 views
0

因为我是cocoa2d的新手,我正在努力沿着圆弧路径旋转物理或动态物体。如何在cocos2d(box2D)中沿着圆弧路径旋转物理或动态物体

我尝试的方式如下:

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

上下面的这种方法我的子画面在圆周运动旋转,而不是在一个弧形路径旋转。

请给出您的意见或建议。

感谢所有

回答

0

我不能完全肯定这是你在找什么,当你谈论一个圆弧轨迹转动来完成。我只看到你设置一个位置,而不是一个旋转,所以你只是想设置一个位置,或一个旋转,或两者兼而有之?由于您在x,y位置使用正弦和余弦,因此您的位置代码看起来像试图实现圆形(或椭圆)路径。

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

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 
} 

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