2014-02-24 90 views
0

我想在SKScene中創建一個UIRotationGestureRecognizer,並將其添加到場景視圖中。當我將該手勢添加到視圖中時,我將它的目標分配給場景,並將該動作分配給場景中的方法。場景的方法永遠不會被調用,並且手勢識別器的視圖屬性始終爲NULL。UIRotationGestureRecognizer無法在SKScene中調用處理程序方法

// 
// MyScene.h 
// Rotate SpaceShip 
// 

// Copyright (c) 2014 Andrew Paterson. All rights reserved. 
// 

#import <SpriteKit/SpriteKit.h> 

@interface MyScene : SKScene <UIGestureRecognizerDelegate> 

@end 

實現:

// 
// MyScene.m 
// Rotate SpaceShip 
// 
// Created by Andrew Paterson on 2/23/14. 
// Copyright (c) 2014 Andrew Paterson. All rights reserved. 
// 

#import "MyScene.h" 
@interface MyScene() 
@property (strong, nonatomic)UIRotationGestureRecognizer *rotationGestureRecognizer; 
@end 
@implementation MyScene 

-(id)initWithSize:(CGSize)size {  
    if (self = [super initWithSize:size]) { 
     /* Setup your scene here */ 

     self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0]; 

     SKSpriteNode *spaceShip = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"]; 
     spaceShip.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); 
     spaceShip.name = @"spaceship"; 

     [self addChild:spaceShip]; 

     self.rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] 
              initWithTarget:self 
              action:@selector(handleRotation:)]; 
     self.rotationGestureRecognizer.delegate = self; 
     [self.view addGestureRecognizer:self.rotationGestureRecognizer]; 
    } 
    return self; 
} 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    /* Called when a touch begins */ 
    [super touchesBegan:touches withEvent:event]; 

} 

-(void)update:(CFTimeInterval)currentTime { 
    /* Called before each frame is rendered */ 
} 
- (void)moveFromScene{ 
    [self.view removeGestureRecognizer:self.rotationGestureRecognizer]; 
} 
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer{ 
    SKSpriteNode *spaceship = (SKSpriteNode *)[self childNodeWithName:@"spaceship"]; 
    if (!(recognizer.state == UIGestureRecognizerStateEnded)){ 

    spaceship.zRotation = (spaceship.zRotation + (recognizer.rotation - spaceship.zRotation)); 

    } 

} 
@end 

調試器輸出這個當我更新的突破和打印手勢識別

(lldb) po self.rotationGestureRecognizer.view 
nil 
(lldb) po self.rotationGestureRecognizer 
<UIRotationGestureRecognizer: 0xa04d570; state = Possible; view = <(null) 0x0>; target= <(action=handleRotation:, target=<MyScene 0x9632380>)>> 
(lldb) 

與解決這個非常奇怪的問題,任何幫助將不勝感激。

回答

0

顯然,在initWithSize中添加手勢識別器時,sprite工具包中存在導致此問題的錯誤:如果將其移動到didMoveToView:問題消失。

+1

這不是一個錯誤。在創建場景時,它尚未呈現,因此其self.view屬性爲零,因此,發送給self.view的任何消息都不會執行任何操作(在此情況下:不添加手勢識別器)。你的修正是正確的,只是假設它是一個錯誤是錯誤的。 ;) – LearnCocos2D

相關問題