本文介绍了在 SKScene 中设置按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 UIButtons 不能很好地与 SKScene 一起工作,所以我试图将 SKNode 子类化以制作一个SpriteKit 中的按钮.

I'm discovering that UIButtons don't work very well with SKScene, So I'm attempting to subclass SKNode to make a button in SpriteKit.

我希望它的工作方式是,如果我在 SKScene 中初始化一个按钮并启用触摸事件,那么该按钮将在我的 SKScene 中调用一个方法,当它被按下.

The way I would like it to work is that if I initialize a button in SKScene and enable touch events, then the button will call a method in my SKScene when it is pressed.

如果有任何建议可以引导我找到此问题的解决方案,我将不胜感激.谢谢.

I'd appreciate any advice that would lead me to finding the solution to this problem. Thanks.

推荐答案

你可以使用 SKSpriteNode 作为你的按钮,然后当用户触摸时,检查它是否是触摸的节点.使用 SKSpriteNode 的 name 属性来标识节点:

you could use a SKSpriteNode as your button, and then when the user touches, check if that was the node touched. Use the SKSpriteNode's name property to identify the node:

//fire button
- (SKSpriteNode *)fireButtonNode
{
    SKSpriteNode *fireNode = [SKSpriteNode spriteNodeWithImageNamed:@"fireButton.png"];
    fireNode.position = CGPointMake(fireButtonX,fireButtonY);
    fireNode.name = @"fireButtonNode";//how the node is identified later
    fireNode.zPosition = 1.0;
    return fireNode;
}

将节点添加到您的场景:

Add node to your scene:

[self addChild: [self fireButtonNode]];

处理触摸:

//handle touch events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location];

    //if fire button touched, bring the rain
    if ([node.name isEqualToString:@"fireButtonNode"]) {
         //do whatever...
    }
}

这篇关于在 SKScene 中设置按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:16