2013-10-08 4 views
1

Я пытаюсь получить доступ к нескольким экземплярам одного и того же объекта, но я не уверен, как это сделать. Я попытался добавить их в массив, но я тоже получаю странную ошибку. Может кто-нибудь, пожалуйста, помогите мне с этим? Я не хочу копировать и запускать этот код 3 раза. Я довольно новичок в этом, так может кто-нибудь объяснить это шаг за шагом?Доступ к нескольким экземплярам одного объекта в Objective C

// 
// C4WorkSpace.m 
// Week_4_Assignment 
// 
// Created by Parth Soni on 2013-10-06. 
// 

#import "C4Workspace.h" 

@implementation C4WorkSpace 
{ 
    C4Shape *circ, *obstacles, *obstacles2, *obstacles3; // the shapes I am building 
    CGRect mycirc, obstacle_circ; 
    CGPoint p, o; // the coordinates of those shapes 
    C4Sample *sample; 
    int glCounter_1, glcounter_2, glcounter_3; 
    BOOL collisionHasHappened ; 
    C4Timer *timer; 

} 

//Setting up the game! 

-(void)setup { 
    //work your magic here 
    collisionHasHappened = FALSE; //Checks if objects have collided 
    [self createShape]; //Creates the Userball 
    [self createObstacles]; // Creates obstacle ball 
    glCounter_1 = 0; // a counter for morphing shapes 

    [self createObstacles_2]; // Creates obstacle ball 
    glcounter_2 = 0; // a counter for morphing shapes 

    [self createObstacles_3]; // Creates obstacle ball 
    glcounter_3 = 0; // a counter for morphing shapes 
    sample = [C4Sample sampleNamed:@"Jump.wav"]; // Audio files 
    [sample prepareToPlay]; // Load the audio 

} 

// Creating Userball 

-(void) createShape { 

    mycirc = CGRectMake(0,0, 100,100); // The Size of the Original Circle 
    p = self.canvas.center; // CG Point 
    circ = [C4Shape ellipse: mycirc]; // It's a Circle! 
    circ.center = p; // The Center of the Circle is P 
    [self.canvas addShape:circ]; // Add THY CIRCLE 
    circ.userInteractionEnabled = NO; // Thy circle has no sense of any interaction thing 

} 

//Creates Obstacles 


-(void) createObstacles { 

    obstacle_circ = CGRectMake(0,0, 50,50); // The Size of the Original Circle 
    o.x += 200; 
    o.y += 300; 
    obstacles = [C4Shape ellipse: mycirc]; // It's a Circle! 
    obstacles.center = o; // The Center of the Circle is P 
    [self.canvas addShape:obstacles]; // Add THY CIRCLE 


} 

-(void) createObstacles_2 { 

    obstacle_circ = CGRectMake(0,0, 50,50); // The Size of the Original Circle 
    o.x += 200; 
    o.y += 300; 
    obstacles2 = [C4Shape ellipse: mycirc]; // It's a Circle! 
    obstacles2.center = o; // The Center of the Circle is P 
    [self.canvas addShape:obstacles2]; // Add THY CIRCLE 


} 

-(void) createObstacles_3 { 

    obstacle_circ = CGRectMake(0,0, 50,50); // The Size of the Original Circle 
    o.x += 200; 
    o.y += 300; 
    obstacles3 = [C4Shape ellipse: mycirc]; // It's a Circle! 
    obstacles3.center = o; // The Center of the Circle is P 
    [self.canvas addShape:obstacles3]; // Add THY CIRCLE 

} 

//Moves the Userball 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Getting Location of Mouse 
    UITouch *place = [[event allTouches] anyObject]; // Get touches 
    CGPoint location = [place locationInView:place.view]; // Gets the location of the current mouse point 
    p.x = location.x-10; 
    p.y =location.y-10; 
    circ.animationDuration = 0.1f; 
    circ.center = p; // The Center of the Circle is P 
    if (!collisionHasHappened){ 
     [self checkForCollision]; 
    } 



} 

-(void) checkForCollision { 


    if(CGRectIntersectsRect(circ.frame, obstacles.frame)) 
    { 

     CGFloat time = 1.0f; // just make a random time frame!!! 
     obstacles.animationDuration = time; // make that the duration now! 
     NSInteger r = [C4Math randomIntBetweenA:75 andB:100]; // How farm from the radius does this need to be? 
     CGFloat theta = DegreesToRadians([C4Math randomInt:360]); // randomizing on which degree will the circle appear. 
       obstacles.center = CGPointMake(r*[C4Math cos:theta] + (300/2), 
             r*[C4Math sin:theta] + (700/2)); 

     [sample play]; 


     collisionHasHappened = TRUE; 
     glCounter_1++; 
     [self checkGameCompletion]; 
     timer = [C4Timer automaticTimerWithInterval:2.0f target:self method:@"collisionActivate" repeats:NO]; 


    } 

    else if(CGRectIntersectsRect(circ.frame, obstacles2.frame)) 
    { 

     CGFloat time = 1.0f; // just make a random time frame!!! 
     obstacles2.animationDuration = time; // make that the duration now! 
     NSInteger r = [C4Math randomIntBetweenA:75 andB:100]; // How farm from the radius does this need to be? 
     CGFloat theta = DegreesToRadians([C4Math randomInt:360]); // randomizing on which degree will the circle appear. 

     obstacles2.center = CGPointMake(r*[C4Math cos:theta] + (300/2), 
             r*[C4Math sin:theta] + (700/2)); 
     [sample play]; 


     collisionHasHappened = TRUE; 
     glcounter_2++; 
     [self checkGameCompletion]; 

     timer = [C4Timer automaticTimerWithInterval:2.0f target:self method:@"collisionActivate" repeats:NO]; 

    } 

    else if(CGRectIntersectsRect(circ.frame, obstacles3.frame)) 
    { 

     CGFloat time = 1.0f; // just make a random time frame!!! 
     obstacles3.animationDuration = time; // make that the duration now! 
     NSInteger r = [C4Math randomIntBetweenA:75 andB:100]; // How farm from the radius does this need to be? 
     CGFloat theta = DegreesToRadians([C4Math randomInt:360]); // randomizing on which degree will the circle appear. 

     obstacles3.center = CGPointMake(r*[C4Math cos:theta] + (300/2), 
             r*[C4Math sin:theta] + (700/2)); 
     [sample play]; 
     glcounter_3++; 
     [self checkGameCompletion]; 

     collisionHasHappened = TRUE; 

     timer = [C4Timer automaticTimerWithInterval:2.0f target:self method:@"collisionActivate" repeats:NO]; 

    } 




    } 



-(void) collisionActivate { 
    collisionHasHappened = FALSE; 

} 


-(void) checkGameCompletion { 

    if (glCounter_1 == 3 && glcounter_2 ==1 && glcounter_3 ==2){ 
     C4Log(@"GAME COMPLETE"); 
    } 
} 

@end 
+0

Это фрагмент кода. Можете ли вы загрузить полный пример? Это облегчит устранение проблем. –

+0

Сделано! Я загрузил все это – tailedmouse

+0

Какая ошибка, и в чем часть кода, с которым вы столкнулись? Это метод 'checkForCollision'? Если да, то что с этим не работает? Постскриптум когда я запускаю этот код, я не получаю ошибок. –

ответ

1

Я думаю, что вы просите что-то вроде этого:

// 
// C4WorkSpace.m 
// Week_4_Assignment 
// 
// Created by Parth Soni on 2013-10-06. 
// 

#import "C4Workspace.h" 

@implementation C4WorkSpace 
{ 
    C4Shape *circ; // the shapes I am building 
    CGRect mycirc, obstacle_circ; 
    CGPoint p, o; // the coordinates of those shapes 
    C4Sample *sample; 
    int glcounter[3]; 
    BOOL collisionHasHappened ; 
    C4Timer *timer; 
    NSMutableArray * myobstacles; 
} 

//Setting up the game! 

-(void)setup { 
    collisionHasHappened = FALSE; //Checks if objects have collided 
    [self createShape]; //Creates the Userball 

    sample = [C4Sample sampleNamed:@"Jump.wav"]; // Audio files 
    [sample prepareToPlay]; // Load the audio 


    myobstacles = [NSMutableArray array]; 
    for (int i = 0; i < 3; i++) 
    { 
     C4Shape * s = [C4Shape ellipse: mycirc]; 
     o.x += 200; 
     o.y += 300; 
     s.center = o; // The Center of the Circle is P 
     [myobstacles addObject:s]; 
     [self.canvas addShape:myobstacles[i]]; // Add THY CIRCLE 
     glcounter[i]=0; 
    } 
} 

// Creating Userball 

-(void) createShape { 

    mycirc = CGRectMake(0,0, 100,100); // The Size of the Original Circle 
    p = self.canvas.center; // CG Point 
    circ = [C4Shape ellipse: mycirc]; // It's a Circle! 
    circ.center = p; // The Center of the Circle is P 
    [self.canvas addShape:circ]; // Add THY CIRCLE 
    circ.userInteractionEnabled = NO; // Thy circle has no sense of any interaction thing 

} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *place = [[event allTouches] anyObject]; // Get touches 
    CGPoint location = [place locationInView:place.view]; // Gets the location of the current mouse point 
    p.x = location.x-10; 
    p.y =location.y-10; 
    circ.animationDuration = 0.1f; 
    circ.center = p; // The Center of the Circle is P 
    if (!collisionHasHappened){ 
     [self checkForCollision]; 
    } 
} 

-(void) checkForCollision { 

    for (int i = 0 ; i < 3; i++) 
    { 
     C4Shape * s = myobstacles[i]; 
     if(CGRectIntersectsRect(circ.frame, s.frame)) 
     { 
      CGFloat time = 1.0f; // just make a random time frame!!! 
      s.animationDuration = time; // make that the duration now! 
      NSInteger r = [C4Math randomIntBetweenA:75 andB:100]; // How farm from the radius does this need to be? 
      CGFloat theta = DegreesToRadians([C4Math randomInt:360]); // randomizing on which degree will the circle appear. 

      s.center = CGPointMake(r*[C4Math cos:theta] + (300/2), 
              r*[C4Math sin:theta] + (700/2)); 
      [sample play]; 
      glcounter[i]++; 
      [self checkGameCompletion]; 

      collisionHasHappened = TRUE; 

      timer = [C4Timer automaticTimerWithInterval:2.0f target:self method:@"collisionActivate" repeats:NO]; 
     } 

    } 
} 

-(void) collisionActivate { 
    collisionHasHappened = FALSE; 

} 

-(void) checkGameCompletion { 

    if (glcounter[0] == 3 && glcounter[1] ==1 && glcounter[2] ==2){ 
     C4Log(@"GAME COMPLETE"); 
    } 
} 

@end 

То, что я сделал это сделал NSMutableArray для хранения экземпляров C4Shape для препятствий. Я также добавил массив int для хранения glcounter. Теперь происходит то, что цикл for создает новый C4Shape, а затем добавляет его в массив. В функции checkForCollision вы найдете еще один цикл for, который выполняет итерацию по массиву и проверяет каждый объект, чтобы увидеть, сталкивается ли он.

Если у вас есть несколько объектов, с которыми вы хотите взаимодействовать, лучше всего подумать о том, чтобы поместить их в массив. Затем вы можете создать новый указатель на объект, с которым хотите поговорить, в то время, когда вы хотите поговорить с ним. Это одна из реальных сил Objective-C.

+0

Woot! хорошо, что это то, что я искал. Супер спасибо! – tailedmouse

+0

Итак, эта строка myobstacles = [NSMutableArray array]; почему у него есть другой изменяемый массив массивов, это как 2d-массив? и является ли это тем, что создает указатель, или он создает другую фигуру objec? C4Shape * s = myobstacles [i]; – tailedmouse

+1

Эта строка является ярлыком для alloc и init. Я мог бы написать [[NSMutableArray alloc] init], но 'array' намного приятнее. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/clm/NSArray/array –

Смежные вопросы