I am trying to move a sprite(ball) within a circular boundary using an accelerometer. I am able to move the sprite(ball) on an empty screen with no difficulties. But now I need to set a circular boundary so that the movement is restricted within the circle. I have a background image which is a circle kind of an image. And if at all the sprite(ball) is moving then it should be only within this circular image and I don't want the ball to move out of the circle image. I want to know how to set the boundary on the circular background image. Please help me. Thanks.
Code:
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];
}