如何使用cocos2d中的加速度计使精灵在圆形边界内移动

时间:2013-03-20 09:49:33

标签: ios5 cocos2d-iphone

我正在尝试使用加速度计在圆形边界内移动精灵(球)。我可以毫无困难地在空屏幕上移动精灵(球)。但是现在我需要设置一个圆形边界,以便在圆圈内限制运动。我有一个背景图像,这是一种圆形的图像。如果所有的精灵(球)都在移动,那么它应该只在这个圆形图像中,我不希望球移出圆形图像。我想知道如何在圆形背景图像上设置边界。请帮我。感谢。

代码:

if((self=[super init])) 
{
  bg=[CCSprite spriteWithFile:@"challenge-game.png"];
      bg.position=ccp(240,160);
      bg.opacity=180;
      [self addChild:bg];

   ball1=[CCSprite spriteWithFile:@"ball.png"];
   ball1.position=ccp(390,180);
   [self addChild:ball1];

    ball2=[CCSprite spriteWithFile:@"ball1.png"];
    ball2.position=ccp(240,20);
    [self addChild:ball2];

    ball3=[CCSprite spriteWithFile:@"ball2.png"];
    ball3.position=ccp(100,180);
    [self addChild:ball3];

    size = [[CCDirector sharedDirector] winSize];
    self.isAccelerometerEnabled=YES;
    [self scheduleUpdate];
  }

 -(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
    {
    ballSpeedY = acceleration.x*20;
     ballSpeedX = -acceleration.y*10;       
   }

-(void)updateBall1 { 
float maxY1 = size.height - ball1.contentSize.height/2;
float minY1 = ball1.contentSize.height/2;
float newY1 = ball1.position.y + ballSpeedY;
newY1 = MIN(MAX(newY1, minY1), maxY1);

float maxX1 = size.width - ball1.contentSize.width/2;
float minX1 = ball1.contentSize.width/2;
float newX1 = ball1.position.x + ballSpeedX;
newX1 = MIN(MAX(newX1, minX1), maxX1);
NSLog(@"MAXY: %f MINY: %f NEWY: %f",maxY1,minY1,newY1);
ball1.position = ccp(newX1, newY1);    
 }

-(void)setPosition:(CGPoint)position
{
 float dx=position.x-240;
 float dy=position.y-160;
 float r=bg.contentSize.width/2-ball1.contentSize.width/2;
 if((dx*dx+dy*dy)>(r*r))
 {
    position.x=100;
    position.y=100;
 }
 [super setPosition:position];
 }

1 个答案:

答案 0 :(得分:0)

不确定剩下的要求是什么,但您是否考虑过使用Box2D并根据加速度计玩重力来移动精灵?在这种情况下,您只需创建一个表示允许世界的圆形对象。

如果这不合适,我想你可以强制你精灵的位置总是在你的圆圈内(覆盖setPosition并确保x和y总是用数学公式给出的圆圈)。

这样的事情(请注意,当球要移出圆圈时,你需要决定将球放在哪里):

-(void) setPosition:(CGPoint)pos
{
    float dx = pos.x - centerX;
    float dy = pos.y - centerY;

    if ((dx * dx + dy * dy) > (r * r))
    {
        // Change pos.x and pos.y to stay within the circle.
    }

    [super setPosition:pos];
}

此外,圆圈的半径(上面代码中的r)实际上应该是目标圆的半径减去球的半径。

使用update

的另一个示例
// In your scene/layer initialization register update callback, like this
[self scheduleUpdate];


// Then modify your update method
- (void) update:(ccTime)delta
{
    // Your update logic

    // Here you take care of your sprite.
    float dx = ballSprite.position.x - centerX;
    float dy = ballSprite.position.y - centerY;

    if ((dx * dx + dy * dy) > (r * r))
    {
        // Change the position of ballSprite to stay within the circle.
        ballSprite.position = ccp(newX, newY);
    }
}
相关问题