我发现UIButtonsSKScene不能很好地配合使用,所以我try 将SKNode子类化为SpriteKit中的一个按钮.

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

如果有任何建议能帮助我找到解决这个问题的办法,我将不胜感激.谢谢.

推荐答案

您可以使用SKSpriteNode作为按钮,然后当用户touch 时,判断这是否是被touch 的 node .使用SKSpriteNode的Name属性标识 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;
}

将 node 添加到场景中:

[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...
    }
}

Ios相关问答推荐

如何在SWIFT中处理不可发送的类型?

SWIFT中具有可选返回类型和泛型的网络请求

我应该使用哪个UIButton发送事件在SWIFT上刷卡?

Flutter 应用程序中带有Firebase的GoogleService-Info.plist中缺少CLIENT_ID、REVERSED_CLIENT_ID和ANDROID_CLIENT-ID

为什么AVSpeechSynthesizer复制的信息比我的文本多?

Swift locationManager.requestWhenInUseAuthorization() 不提示用户

使用异步重载实现Swift协议一致性

不可发送类型 '[String : Any]?'在调用非隔离实例方法 XXX 时退出主参与者隔离上下文不能跨越参与者边界

SwiftUI 中的描边图像边框

添加到单个自定义视图时,Swiftui 项目会在所有视图中重复

SwiftUI - ScrollView 不显示底部文本

SensorKit - 获取数据不调用结果委托函数

禁用 UITextField 的自动更正

检测 iPhone 应用程序中是否存在摄像头?

如何找出坐标之间的距离?

改变 UIView 位置的简单方法?

是否可以在 iOS 9 上让您的 iPad 应用退出多任务处理?

使用 Swift 在一个 ViewController 中强制横向模式

为给定的 UIColor 获取更亮和更暗的 colored颜色 变化

AFNetworking 发布请求