2014-08-31 73 views
0

我正在嘗試使用SKSpriteNode在sprite工具包中創建一個按鈕。我想讓按鈕圖像在按下時更改,並在按下按鈕後立即恢復爲舊圖像。我所做的到現在是以下幾點: -如何在sprite工具包中創建按鈕iOS(類似於切換按鈕)

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

self.startTouch = [[touches allObjects][0] locationInNode:self ]; 
for (UITouch *touch in touches){ 

     CGPoint position = [touch locationInNode:self]; 
     SKNode *node = [self nodeAtPoint:position]; 

     if ([node.name isEqualToString:@"missileButton"]) { 
       TEMissileButtonNode *button = (TEMissileButtonNode*) node; 
       button.isPressed = YES; 
      } 
    } 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
for (UITouch *touch in touches){ 

    CGPoint position = [touch locationInNode:self]; 
    SKNode *node = [self nodeAtPoint:position]; 

    if ([node.name isEqualToString:@"missileButton"]) { 
     TEMissileButtonNode *button = (TEMissileButtonNode*) node; 
     button.isPressed = NO; 
    } 
} 

} 

update方法裏面我打電話此方法來檢查,如果觸摸已經結束

-(void)changeMissileButton{ 
if (self.missileButton.isPressed) { 
    [self.missileButton addMoreMissileButtons]; 
    [self.missileButton setTexture:[SKTexture textureWithImageNamed:@"missileButtonPressed"]]; 
}else{ 
    [self.missileButton setTexture:[SKTexture textureWithImageNamed:@"missileButtonDeselected"]]; 
    [self.missileButton hideMissileButtons]; 
} 

} 

的問題是,觸摸沒有得到有時登記。有時它按我想要的方式工作。當我觸摸它時,其紋理會發生變化,當我移開手指時,紋理會恢復到舊紋理。但大多數時候,按鈕對我的觸摸沒有反應。我錯過了什麼嗎?

+0

你在哪裏調用'changeMissileButton'方法? – ZeMoon 2014-08-31 16:05:34

+0

主場景的更新方法 – 2014-09-01 07:05:39

+0

這可能是問題...你每秒設置紋理60次!嘗試在每個案例的changeMissileButton方法中使用NSLog,並檢查方法如何從更新中調用:方法 – ZeMoon 2014-09-01 07:11:59

回答

0

使用touchesBegan,touchesMoved,touchesEnded。

touchesBegan - 檢查按鈕(SKSpriteNode)是否包含觸摸。如果是這樣,改變你的按鈕紋理。

touchesMoved-如果按鈕不包含觸摸,則將紋理更改回來。

touchesEnded-如果在touchesMoved時觸摸停留在按鈕內,請將紋理更改回來。

以上是如何高效完成您所要做的工作的邏輯。是的,這是令人討厭的Spritekit決定放棄按鈕。