2012-09-16 51 views
0

需要幫助。我一直被困在這個問題上很多天... 我正在做一個觸摸殺鳥的射擊遊戲。 當鳥被觸摸時,將其與動畫其血液噴濺.. 圖像陣列模具和鳥是靜態的,並且有時其飛.. 我可以用下面的代碼很容易做到的靜態部分:如何在CALayer上添加UIImageView?

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{UITouch *mytouch=[[touches allObjects] objectAtIndex:0]; 
    if ([touches count]==1) 
    {  
    location = [mytouch locationInView:self]; 
    UIView *killView = [self hitTest:location withEvent:nil]; 

    if ([killView isKindOfClass:[UIImageView class]]) { 
     birdKilled = YES; 
     [self addSubview:[self bloodSplash:killView]];}}} 



-(UIImageView *)bloodSplash:(UIView*)killedView { 
    UIImageView *blood = [[UIImageView alloc] 
      initWithFrame:CGRectMake(killedView.center.x-100.0/2.0, killedView.center.y-100.0/2.0, 100, 100)]; 
    [killedView setHidden:YES]; 
    blood.image = [bloodExplodes objectAtIndex:2]; 
    [blood setAnimationImages:bloodExplodes]; 
    [blood setAnimationDuration:0.4]; 
    [blood setAnimationRepeatCount:1]; 
    [blood startAnimating];    
    [self performSelector:@selector(cleanBlood:) withObject:blood afterDelay:.8]; 
    return [blood autorelease];} 

但是對於飛行部分,我真的被卡住了! 因爲我知道當我動畫飛鳥時。 我需要在hitTest中檢測其表示層。 我可以用「UIViewAnimationOptionAllowUserInteraction」成功地實現它..但問題是我無法弄清楚如何將bloodSplash函數添加到接觸點,因爲它將UIImageView返回給CALayer .. 這是我的試用版。

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

    if ([flyingBird.layer.presentationLayer hitTest:location]) { 
    CALayer* touchedLayer = 
     [flyingBird.layer.presentationLayer hitTest:location]; 
    //No Idea what to do next.. 
    }} 

因爲我真的不知道什麼關於layers..Thx的任何建議。

回答

0

爲了將圖像視圖添加到您的飛鳥視圖中,您需要找到正確的視圖。 UIView由CALayer支持,並且該圖層具有UIView作爲其委託。 當您製作動畫時,您需要在表示層上進行測試,然後返回到模型圖層,因爲這是與您相關的。從那裏你可以通過查詢圖層的委託來找到相應的UIView。 因此,這將是這個樣子:

CALayer *hitLayer = [[flyingBird.layer.presentationLayer hitTest:location] modelLayer]; 
UIView *hitView = [hitLayer delegate]; 

這應該是您可以在動畫的UIImageView添加到視圖。

+0

thx爲您的幫助!但我發現它並不完美。 hitView實際上捕捉飛鳥的最終位置,當我添加動畫UIImageView ..它播放幀... – Walter

+0

相反,我找到了另一種方式來做它.. CGRect killRect = [flyingBird.layer.presentationLayer框架]。如果(CGRectContainsPoint(killRect,location){self addSubview:[self bloodSplash:killRect]];} 通過此版本,我可以將動畫UIImageView添加到擊中位置..但是,我有另一個問題..我可以多次殺死死鳥,因爲我無法像以前那樣將UIImageView userInteractionEnabled設置爲NO ....任何想法?? – Walter

+0

我可以提出另一個問題......以避免多次殺死同一只鳥。 ...現在我的代碼變成.. ** if(CGRectContainsPoint([flyingBird.layer.presentationLayer frame],location){CGRect killRect = [flyingBird.layer.presentationLayer frame]; [flyingBird.layer removeFromSuperlayer]; [ self addSubview:[self bloodSplash:killRect]];} ** 但它不工作..下一次我點擊位置.. flyingBird.presentation.layer依然存在.. 我也試過** [flyingBird removeFromSuperview]; ** 但我仍然可以點擊...請幫助! – Walter