【问题标题】:How to create button in sprite kit iOS (similar to toggle button)如何在精灵套件 iOS 中创建按钮(类似于切换按钮)
【发布时间】:2014-09-02 23:42:38
【问题描述】:

我正在尝试使用 SKSpriteNode 在精灵工具包中制作一个按钮。我希望按钮图像在按下时发生变化,并在按下结束后立即恢复为旧图像。我到目前为止所做的如下:-

-(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;
    }
}

}

在更新方法中我调用这个方法来检查触摸是否结束

-(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];
}

}

问题是有时无法注册触摸。有时它会按我想要的方式工作。当我触摸它时,它的纹理会发生变化,当我移开手指时,纹理会恢复到旧纹理。但大多数时候,按钮对我的触摸没有反应。我错过了什么吗?

【问题讨论】:

  • 你在哪里调用changeMissileButton方法?
  • 主场景的更新方法里面
  • 这可能是问题所在...您每秒设置纹理 60 次!尝试在每种情况下的 changeMissileButton 方法中使用 NSLog,并检查方法在从更新中调用时的行为:方法
  • 我尝试将 NSLog 及其每秒打印 60 次,但问题是没有其他方法。我还能如何检测按钮的变化。它也不是一个 ui 按钮,而是一个精灵节点。我希望按钮在手指离开按钮后立即将纹理恢复为原始纹理。有什么建议吗?
  • 可以在 touchesBegan 和 touchesEnded 方法本身中设置纹理。

标签: ios button sprite-kit


【解决方案1】:

使用 touchesBegan、touchesMoved、touchesEnded。

touchesBegan - 检查按钮 (SKSpriteNode) 是否包含触摸。如果是这样,请更改您的按钮纹理。

touchesMoved- 如果按钮不包含触摸,则将纹理改回来。

touchesEnded- 如果在 touchesMoved 期间触摸停留在按钮内,则将纹理改回。

以上是如何有效地完成您正在尝试做的事情的逻辑。是的,Spritekit 决定放弃按钮很烦人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 2013-01-19
    • 2016-03-05
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多