2014-10-23 6 views
0

내 터치 내에서 배열을 시작했습니다 (나는 스프라이트를 터치 할 수 있고 NSlog 터치를 원할 수 있습니다.) 뭔가 잘못하고 있는거야?작동하지 않는 배열의 항목을 만지려고합니다

화면에 터치를 기록 할 수 있지만 거품을 터치해도 아무런 변화가 없습니다. 도움이 될 것입니다.

-(id) init 
{ 
if((self=[super initWithColor:ccc4(10, 10, 10,10)])) //sand 101, 116, 88 
{ 
    size = [[CCDirector sharedDirector] winSize]; 
    self.touchEnabled = YES; 

//other stuff here 

Bubble01 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255  gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@",  [Sortingarray objectAtIndex:BubbleAnswerBubble_1_IndexValue]]]; 
    Bubble02 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255 gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@", [Sortingarray objectAtIndex:BubbleAnswerBubble_2_IndexValue]]]; 
    Bubble03 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255 gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@", [Sortingarray objectAtIndex:BubbleAnswerBubble_3_IndexValue]]]; 
    Bubble04 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255 gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@", [Sortingarray objectAtIndex:BubbleAnswerBubble_4_IndexValue]]]; 
    Bubble05 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255 gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@", [Sortingarray objectAtIndex:BubbleAnswerBubble_5_IndexValue]]]; 
    Bubble06 = [[Bubble alloc]initWithBubbleWithLabel:@"_Bubble.png" opacity:255 gloss:@"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:@"%@", [Sortingarray objectAtIndex:AnswerBubble_6_IndexValue]]]; 

//other stuff here 

} 
return self; 
} 

touchesbegan 어떤 통찰력이 나를 내가 잘못 이해하는 데 도움 좋을 것

-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
//set up touches 
NSSet *allTouch = [event allTouches]; 
UITouch *touch = [[allTouch allObjects]objectAtIndex:0]; 
CGPoint location = [touch locationInView:[touch view]]; 
location = [[CCDirector sharedDirector]convertToGL:location]; 

//log if touches are working if I touch the screen area 
NSLog(@"touches screen"); 

//create an array from bubble class (CCSprites with labels, 
//I need to be able to determine which sprite was touched and run an action on it) 

BubbleArray = [[NSMutableArray alloc]initWithObjects:Bubble01, 
       Bubble02, 
       Bubble03, 
       Bubble04, 
       Bubble05, 
       Bubble06, 
       nil]; 

    for(int i = 0; i < [BubbleArray count]; i++) 
    { 

    Bubble *sprite = (Bubble *)[BubbleArray objectAtIndex:i]; 

    //create a rect to find the position and size of the sprite 
    //BackBubble is a sprite that i'm using to detect the content size 

    CGRect targetRect = CGRectMake(

      sprite.BackBubble.position.x - (sprite.BackBubble.contentSize.width/2), 
      sprite.BackBubble.position.y - (sprite.BackBubble.contentSize.height/2), 
      sprite.BackBubble.contentSize.width, 
      sprite.BackBubble.contentSize.height); 

    //use the rect and touch location to determine hit 
    if(CGRectContainsPoint(targetRect, location)) 

    //this doesn't work possibly because Bubble class is a CClayer? 

    //if(CGRectContainsPoint([sprite boundingBox], location)) 
    { 
     selectedSprite = sprite; 
     NSLog(@"touches bubble sprite"); 
    } 
} 

}

. 환호 :)

새로운 배열 코드 (

for(int i = 0; i < [DragItems count]; i++) 
    { 


    Bubble *sprite = (Bubble *)[BubbleArray objectAtIndex:i]; 
    location = [sprite convertToNodeSpace:location]; 

    if(CGRectContainsPoint([sprite.BackBubble boundingBox], location)) 
    { 
     selectedSprite = sprite; 
      NSLog(@"touches bubble"); 
    } 
    } 

Bubble.m

#import "Bubble.h" 
#import "Common.h" 

#define ButtonFlashTime .4 
#define KBubbleColourTurqoiseBlueFlash 2323 
#define ScrollSpeed 5.2f 
#define DecoyTextY 5 
#define DecoyTextX -2 


@implementation Bubble 
@synthesize BackBubble,FrontShine,BubbleLabel,startX,startY,currentY,currentX,isNotTouchActivated,myInt,bubblespeed,tagNumber; //isTouched 

-(id)init 
{ 
    self=[super init]; 
    { 
     //touches 
     [[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES]; 
     isNotTouchActivated = false; 
     isTouched = NO; 

     bubblespeed = 0; 

     //start scrolling 
     [self MoveWithoutProblem]; 

     [self setAnchorPoint:ccp(0.5,0.5)]; 

     BackBubble = [CCSprite spriteWithSpriteFrameName:Bubblepng]; 
     BackBubble.position = ccp(X,Y); 
     [BackBubble setAnchorPoint:ccp(0,0)]; 
     [self addChild: BackBubble z:5]; 
     NSLog(@"BackBubble, %f %f",BackBubble.position.x,BackBubble.position.y); 

     //other code here 

     [self setContentSize:[BackBubble boundingBox].size]; 

    } 
    return self; 
} 



-(BOOL) isTouchOnSprite:(CGPoint)touch{ 
    CGPoint local = [self convertToNodeSpace:touch]; 
    CGRect r = self.boundingBox; 
    r.origin = CGPointZero; 
    Boolean b = CGRectContainsPoint(r, local); 
    //CCLOG(@"touch %f : %f : %d",touch.x,touch.y,b); 
    if (b) { 
     return YES; 
    }else { 
     return NO; 
    } 
} 
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{ 
    CGPoint touchPoint = [touch locationInView:[touch view]]; 
    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint]; 
    if([self isTouchOnSprite:touchPoint]){ 
     //CGPoint move = [self convertTouchToNodeSpace:touch]; 
     isNotTouchActivated = TRUE; 
     //isTouched = YES; 
     //NSLog(@"isTouched = %@", self.isTouched ? @"YES" : @"NO"); 
     currentX = touchPoint.x; 
     currentY = touchPoint.y; 
     self.position = touchPoint; 
     return YES; 
    } 
    // NSLog(@"isTouched = %@", self.isTouched ? @"YES" : @"NO"); 
    return NO; 

} 
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{ 
    CGPoint touchPoint = [touch locationInView:[touch view]]; 
    touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint]; 
    if (isNotTouchActivated) { 
     currentX = touchPoint.x; 
     currentY = touchPoint.y; 
     self.position = touchPoint; 
    } 
} 
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{ 
    isNotTouchActivated = FALSE; 
    //isTouched = NO; 
} 
-(void)MoveWithoutProblem{ 


    CGSize size = [[CCDirector sharedDirector] winSize]; 

    int MaxHeightofBubbles = 350; 
    int minHeightofBubbles = 150; 
    int RandomNumber = [self generateRandomNumberBetweenMin:minHeightofBubbles Max:MaxHeightofBubbles]; 
    float ConvertedRandom = [[NSNumber numberWithInt: RandomNumber] floatValue]; 

    int MaxWidthofBubbles = 0; 
    int minWidthofBubbles = 900; 
    int RandomNumber02 = [self generateRandomNumberBetweenMin:MaxWidthofBubbles Max:minWidthofBubbles]; 
    float ConvertedRandom02 = [[NSNumber numberWithInt: RandomNumber02] floatValue]; 

    startX = ConvertedRandom02; 

    startY = ConvertedRandom; 

    currentX = startX+myInt; 
    currentY = startY; 
    self.position = ccp(startX,startY); 

    [self schedule:@selector(startMoving)]; 
} 



-(void)startMoving{ 
    if (!isNotTouchActivated) { 



     currentX+=bubblespeed; 
     [self setPosition:ccp(currentX,currentY)]; 
    } 

    if (self.position.x >= 1024+50) { 
     //NSLog(@"off screen"); 

     isrestartscrolling = YES; 
    } 

    if (isrestartscrolling == YES) { 
     //[self RandomYPOs]; 
     [self scheduleOnce:@selector(newRandomX) delay:0.2]; 
     isrestartscrolling = NO; 
    } 

} 

@end 
+0

장면에 스프라이트를 추가하는 위치가 표시되지 않습니다. [[[[CCDirector sharedDirector] openGLView] 창] addSubview : ]; 다음 [ addTarget : 자기 액션 : @selector (yourfunction :) forControlEvents : UIControlEventTouchDragInside]; – user3344236

+0

버블 스프라이트가 init에 추가되었습니다. (죄송합니다. 그 코드도 거기에 넣습니다.) – StackBuddy

답변

1

에 코드를 사용자 정의 클래스를 통해 스프라이트의 높이와 폭을 점점 읽기 조금 어렵지만 귀하의 즉각적인 문제가 터치가 작동하지 않는 이유는 레이어 (Bubble)의 내용 너비와 높이가 있다고 가정하기 때문입니다. 설정하지 않은 경우에는 그렇지 않습니다. 따라서 주석 처리 된 줄 [sprite boundingBox] 시도하지 않습니다. 시도하십시오 [sprite.BackBubble boundingBox]. 레이어에 항목을 추가해도 해당 레이어의 콘텐츠 크기가 자동으로 조정되지 않습니다.

넌 할 수있어 또 하나 추가하는 것입니다 : 당신의 기포 층 또는 다시 거품이 단순히 CGRect에 다시 거품의 위치를 ​​추가 한 후 어느 시점에 이동하는 경우

location = [sprite convertToNodeSpace:location]; 

일 가능성이 없습니다. 첫 번째 아이디어를 먼저 시도한 다음 문제가 해결되지 않으면 시도하십시오.

희망이 도움이 나탈리.

+0

감사합니다. Allen, 흠, 내가 이해하지 못해 죄송합니다 ... 그래서 "CGRect targetRect"를 만들면 너비가 지정되지 않습니다. 스프라이트의 높이? (나는 새로운 개념이므로이 모든 작업 방법을 이해하려고 노력하고 있지만 바운딩 박스 솔루션을 시도해 보았습니다. 그러나 불행히도 (거품 구조) 레이어는 자체적으로 (드래그하지만 충돌이 아닌) 핸들을 처리합니다. 하지만 처음으로 Ive는 자체 터치 감지 (게임 레이어에서 나는 다른 클래스에서 작동하도록 충돌을 시도하고 있음)를 사용하는 스프라이트 클래스를 만들었습니다. 제대로 사용하는 방법과 관련하여 일부 문제가 생겼습니다. – StackBuddy

+0

죄송합니다. , 나는 'Bubble' 인스턴스에 대해 이야기하고있었습니다. 코드에있는 당신의 코멘트는 그것이'CCLayer '이기 때문에 Bubble의 테두리 상자가 작동하지 않는지 묻습니다. 레이어에 객체를 추가 할 때 레이어의 너비와 높이가 설정되지 않습니다. 레이어에 폭과 높이를 특별히 지정하지 않는 한,'Bubble' (레이어라고 말한) 오브젝트는 내용 크기를 가지지 않기 때문에'[sprite boundingBox]'가 작동하지 않을 것입니다. –

+0

또한 수정 된 코드에서 적절한 r을 얻지 못합니다. 왜냐하면 원래의 터치 위치를 사용하지 않기 때문입니다. 반복 할 때마다 하나의 Bubble 공간으로 변환 된 값을 가져 와서 각 계산에 원래의 터치 위치를 사용하는 대신 다른 Bubble 공간으로 변환하려고합니다.'CGPoint localLocation = [sprite convertToNodeSpace : location];과 같은 것을 시도하고'CGRectContainsPoint()'호출에서 이것을 사용하십시오. –