点击或拖动节点时节点不一致

时间:2017-01-04 13:19:14

标签: ios sprite-kit

我希望我的SKSpritenodes在点击并在屏幕上拖动时放大(放大)。当用户移除触摸输入时,他们需要缩小最后一个位置。这是我现在用来实现这种效果的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let card = atPoint(location) as? Card
        if card?.cardType == .main{
            card?.zPosition = 30
            card?.run(SKAction.scale(to: 1.3, duration: 0.15))
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let card = atPoint(location) as? Card
        if card?.cardType == .main{
            card?.zPosition = 30
            card?.removeFromParent()
            addChild(card!)
            card?.run(SKAction.scale(to: 1.0, duration: 0.15))
        }
    }
}

Card是我定义的一个继承自SKSpriteNode的类。

问题似乎是,有时当我触摸精灵节点时,它们不会向上扩展,有时则会缩放。当我拖动它们时,似乎动画看起来非常迟钝。此外,当我放下节点(即移除触摸输入)时,缩小效果也不会一致地发生(有时它会发生,有时它不会)。到底是怎么回事?如果你们需要更多的源代码,请告诉我。

1 个答案:

答案 0 :(得分:3)

请不要复制并粘贴此答案,尝试自己完成工作,并将您的代码与此答案进行比较。

如何修复缩放问题:

当您调用run action时,新操作不会取消上一个操作,因此发生的情况是您同时运行这两个操作,这可能会发生冲突。相反,请使用键删除上一个操作。

如何修复拖动问题:

您需要在触摸开始方法中保留正在拖动的节点。然后,当您进行拖动时,您将知道要设置的位置。

另请参阅我如何清理代码以减少行数并删除&#39;?&#39;在很多变量调用中。在你去使用之前?要么 !在一个变量来解决你的问题,检查是否有更好的方法来处理代码流。使用 !只有当你可以100%保证nil永远不会发生并且包装在temp变量中效率低下时。使用 ?只有当你期望代码继续时,即使变量是nil并且包装在temp变量中也是低效的。

如果您碰巧需要变量与您正在使用的函数位于同一范围内,那么您可能需要考虑使用guard。守卫的工作方式是,如果不符合某些条件,它将退出当前范围,例如,如果您在代码中指出卡片必须存在超过此点的位置,那么您执行guard let card = atPoint(location) as? Card。有关防范的更多信息,请参阅http://nshipster.com/guard-and-defer/以更好地了解其工作原理。

var movableCard : Card?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)

        if let card = atPoint(location) as? Card, card.cardType == .main{
            card.zPosition = 30
            movableCard = card
            //Not sure what node this card is suppose to move to
            card.run(SKAction.scale(to: 1.3, duration: 0.15),withKey:"scaling")
        }
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if let card = movableCard{

            card.position = location
        }
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)

        if let card = movableCard{
            card.zPosition = 30
            card.moveToParent(self)
            movableCard = nil
            card.run(SKAction.scale(to: 1.0, duration: 0.15),withKey:"scaling")
        }
    }
}