问题描述
我发现 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;
}
为您的场景添加节点:
[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中设置按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!