开发者

how to detect touch in a circle

开发者 https://www.devze.com 2023-04-11 10:21 出处:网络
I really assistance. Im a little confused. i have a circle sprite, and this code -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

I really assistance. Im a little confused. i have a circle sprite, and this code

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

CGSize winSize =[[CCDirector sharedDirector] winSize];
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

CCSprite *circleSprite = (CCSprite*)[self getChildByTag:30];
CGRect correctColorSprite1 = [circleSprite boundingBox];

   if (CGRectContainsPoint(correctColorSprite1, location)) {
   NSLog(@"inside");

}

as i know there is a bounding box, when i touch slightly outside of the top circle it will still detect the touch.

i have read in some forums that i need to detect dist开发者_高级运维ance of the centre of the sprite and the touch point. But i really don't know how to write that code. My circle size is around 50 points.

I hope someone can help me out give me some snippets of a improved code to detect the touch only in the circle. Not with the bounding box. Your help is very great full.


Try this:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{

CGSize winSize =[[CCDirector sharedDirector] winSize];
UITouch* myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView: [myTouch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

CCSprite *circleSprite = (CCSprite*)[self getChildByTag:30];
//CGRect correctColorSprite1 = [circleSprite boundingBox];
CGRect correctColorSprite1 = CGRectMake(
    circleSprite.position.x - (circleSprite.contentSize.width/2), 
    circleSprite.position.y - (circleSprite.contentSize.height/2), 
    circleSprite.contentSize.width, 
    circleSprite.contentSize.height);

//find the center of the bounding box
CGPoint center=ccp(correctColorSprite1.size.width/2,correctColorSprite1.size.height/2);

//now test against the distance of the touchpoint from the center
   if (ccpDistance(center, location)<50) 
   {
     NSLog(@"inside");

   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号