【问题标题】:Dragging and dropping sprites without hardcoding names using swift [closed]使用swift拖放没有硬编码名称的精灵[关闭]
【发布时间】:2014-07-20 23:20:31
【问题描述】:

我只是想让用户在屏幕上拖放某些精灵。我看到的答案是检查精灵的名称(如下所示)。必须有更好的方法来做到这一点。感谢您的任何意见。

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    var nodeTouched = SKNode()
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        nodeTouched = self.nodeAtPoint(location)

        if(nodeTouched.name? == "character") {
            character.position=location
            currentNodeTouched = nodeTouched
        } else {
            currentNodeTouched.name = ""
        }
    }
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        var nodeTouched = SKNode()
        nodeTouched = self.nodeAtPoint(location)

        if(currentNodeTouched.name == "character") {
            character.position = location
        }
    }
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)

        var nodeTouched = SKNode()
        nodeTouched = self.nodeAtPoint(location)

        if(currentNodeTouched.name == "character") {
            character.position = location
        }
    }
}

【问题讨论】:

    标签: swift sprite-kit ios8 skspritenode sknode


    【解决方案1】:

    由于您只想拖放特定的精灵,因此必须有一种识别它们的方法。这可以是任何可以用来区分节点的东西。以下是关于在这种情况下可以使用什么的一些建议。

    答案中的代码是Objective-C,希望你能翻译成Swift。

    name 属性

    正如你所说,这是最常用的判断精灵是否可以拖动的方法。

    userData 属性

    这是与 SKNode 关联的属性,可让您设置所需的任何自定义数据。你可以阅读它here

    [node.userData setValue:@(YES) forKey:@"draggable"]; //Setting the value
    
    if ([[node.userData valueForKey:@"draggable"] boolValue]) //Checking the value
    

    子类化

    您还可以创建一个自定义类,该类可以自行处理 deag-drop 功能,也可以将 BOOL 实现为可以在触摸委托中检查的属性。

    类名

    在某些情况下,您可能只想拖动特定类的节点。

    if ([node isKindOfClass:[CustomNode class]])
    
    if ([(NSStringFromClass([node class]) isEqualToString:@"CustomNode"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      相关资源
      最近更新 更多