Cocos2d:基于加速度计的动画

时间:2011-12-05 06:27:48

标签: animation cocos2d-iphone accelerometer

任何人都知道任何最新的教程,其中展示了如何根据加速度计的运动动画精灵。我想动画一只鸟动摇到设备指向的位置。例如,如果玩家决定通过加速度计将鸟移动到左侧,我希望我的小鸟能够播放向左摇摆的动画。

// Accelerometer
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration   *)acceleration { 
birdSpeedY = 9.0 + acceleration.x*15;
birdSpeedX = -acceleration.y*20;
}

// Updating bird based on accelerometer
-(void)updateBird { 
float maxY = winSize.height - bird.contentSize.height/2;
float minY = bird.contentSize.height/2;
float newY = bird.position.y + birdSpeedY;
newY = MIN(MAX(newY, minY), maxY);

float maxX = winSize.width - bird.contentSize.width/2;
float minX = bird.contentSize.width/2;
float newX = bird.position.x + birdSpeedX;
newX = MIN(MAX(newX, minX), maxX);

bird.position = ccp(newX, newY);
}

// Making background scroll automatically 
-(void)update:(ccTime)dt { 
[self updateBird];

CGPoint backgroundScrollVel = ccp(-100, 0);
parallaxNode.position = ccpAdd(parallaxNode.position, ccpMult(backgroundScrollVel, dt));


}


-(id)init {
self = [super init];
if (self != nil) {
   winSize = [CCDirector sharedDirector].winSize;

    CCSpriteFrameCache *cache=[CCSpriteFrameCache sharedSpriteFrameCache];
    [cache addSpriteFramesWithFile:@"birdAtlas.plist"];

    NSMutableArray *framesArray=[NSMutableArray array];
    for (int i=1; i<10; i++) {
        NSString *frameName=[NSString stringWithFormat:@"bird%d.png", i];
        id frameObject=[cache spriteFrameByName:frameName];
        [framesArray addObject:frameObject];
    }
    // animation object
    id animObject=[CCAnimation animationWithFrames:framesArray delay:0.1];

    // animation action
    id animAction=[CCAnimate actionWithAnimation:animObject restoreOriginalFrame:NO];
    animAction=[CCRepeatForever actionWithAction:animAction];


    bird=[CCSprite spriteWithSpriteFrameName:@"bird1.png"];
    bird.position=ccp(60,160);



    CCSpriteBatchNode *batchNode=[CCSpriteBatchNode batchNodeWithFile:@"birdAtlas.png"];
    [self addChild:batchNode z:100];
    [batchNode addChild:bird];

    [bird runAction:animAction];

    self.isAccelerometerEnabled = YES; 
    [self scheduleUpdate]; 

    [self addScrollingBackgroundWithTileMapInsideParallax];
  }
  return self;
}

- (void) dealloc
{
[super dealloc];
}


@end

1 个答案:

答案 0 :(得分:0)

您可以尝试使用Accelerometer方法并使用ccp()更改Sprite的位置。您还需要知道模式中的横向或纵向项目。 你可以试试下面的东西

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration
{   
    [lbl setString:[NSString stringWithFormat:@"X=>%.2lf Y=>%.2lf",(double)acceleration.x,(double)acceleration.y]];
    double x1= -acceleration.y *10;
    double y1=  acceleration.x *15;
    if(acceleration.x >0.05)
    {
         y1*=spped_incr; // Make Movement Here

    }
    [Sprite_Name runAction:[CCMoveTo actionWithDuration:0.1f position:ccpAdd(ccp(x1,y1), Sprite_Name.position)]];
}

以上材料适用于横向模式....如果您需要在纵向模式下需要更改轴并使用TRY&amp;错误方法。