长按结束时如何 运行 函数 swift sprite kit

How to run a function when a long press has ended swift sprite kit

我是 运行 一个非常简单的代码,我试图检测长按何时结束,然后执行一个函数,但我似乎无法弄清楚该怎么做。我已经在网上查看了很多资源,但一直无法弄清楚。我对 Swift 中的编码非常陌生,所以如果答案很简单,我提前道歉。这是所有代码:

import SpriteKit

class GameScene: SKScene {

    let char = SKSpriteNode(imageNamed: "flying character")

    override func didMove(to view: SKView) {
        setScene()
    }

    @objc func press() {
        physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
        if UILongPressGestureRecognizer.State.changed == .ended {
            print ("the gesture has ended")
        }
    }

    func setScene() {
        backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 221/255, alpha: 1.0)
        char.size = CGSize(width: frame.size.width/5, height: frame.size.width/5)
        char.run(SKAction.rotate(byAngle: .pi*11/6, duration: 0.00001))
        char.position = CGPoint(x: frame.midX - 100, y: frame.midY + 150)
        addChild(char)
        char.physicsBody = SKPhysicsBody(circleOfRadius: char.size.width/2)
        char.physicsBody?.categoryBitMask = PhysicsCategories.charCategory
        physicsWorld.gravity = CGVector(dx: 0.1, dy: -1.5)
        char.physicsBody?.affectedByGravity = true
        view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press)))
    }
}

如您所见,我只是在长按结束时尝试执行打印命令。

首先,您可能注意到的一件非常重要的事情是您的问题与 SpriteKit 本身无关!您正在使用 UILongPressGestureRecognizer,来自 UIKit 的 class! Apple Docs

另外请注意,您正在将手势应用于整个视图。因为我假设这是一款角色会飞的游戏,所以我认为这种行为是有意为之的。

我想您面临的问题是您没有使用分配给您的视图的 UILongPressGestureRecognizer!相反,您正在访问 UILongPressGestureRecognizer class properties/methods。更多详情您可以浏览this section of the Swift documentation


解决您问题的一个快速方法是将您的按压功能从

更改为
@objc func press() {
    physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
    if UILongPressGestureRecognizer.State.changed == .ended {
        print ("the gesture has ended")
    }
}

@objc func press(_ gestureRecognizer: UILongPressGestureRecognizer) {
    physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
    if gestureRecognizer.state == .ended {
        print ("the gesture has ended")
    }
}

和您的 setScene 函数来自

view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press)))

view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press:)))

More information here


SpriteKit 以一种非常原始的方式处理触摸事件,但它可能会让您对如何响应这些事件有更多的控制。正如KnightOfDragon所说,这就像重新发明轮子。

如果你想看看 SpriteKit 是如何做到的,see this example.它很短,但我希望它对你有所帮助:)