在 xcode 和 swift 中使用选择器

using selector in xcode with swift

运行 今天我的编码遇到了一些麻烦。试图制作 "automatic" 武器,但无法让选择器正常工作。 这是代码

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in (touches ){
        let location = touch.location(in: self)func spawnBullets(){
                let Bullet = SKSpriteNode(imageNamed: "circle")
                Bullet.zPosition = -1
                Bullet.position = CGPoint(x: ship.position.x,y: ship.position.y)
                Bullet.size = CGSize(width: 30, height: 30)

                Bullet.physicsBody = SKPhysicsBody(circleOfRadius: 15)
                Bullet.physicsBody?.categoryBitMask = PhysicsCategory.Bullet

                Bullet.name = "Bullet"
                Bullet.physicsBody?.isDynamic = true
                Bullet.physicsBody?.affectedByGravity = false
                self.addChild(Bullet)

                var dx = CGFloat(location.x - base2.position.x)
                var dy = CGFloat(location.y - base2.position.y)

                let magnitude = sqrt(dx * dx + dy * dy)

                dx /= magnitude
                dy /= magnitude

                let vector = CGVector(dx: 30.0 * dx, dy: 30.0 * dy)
                Bullet.physicsBody?.applyImpulse(vector)


            }
            spawnBullets()
            Timer.scheduledTimer(timeInterval: 0.2, target: self, selector:#selector("spawnBullets"),userInfo: nil, repeats: true)
        }

' 然而,当我 运行 这个时,我得到一个错误,选择器没有引用任何东西。谁能帮助我吗? 谢谢

您没有添加正在使用的 swift 版本。 swift 3.x.

有一些细微的变化

在 swift 3.x 中,您不会以这种方式使用带引号的选择器,因此您必须删除引号并执行以下操作:

selector:#selector(spawnBullets)

这也会在更改代码时为您提供一些类型安全。因此,当你做错事时,你会得到编译时错误,而不是运行时错误。

对于你的情况,我也会做的是将函数 spawnBullets 移到 touchBegan 之外,如下所示:

func spawnBullets(_ location: CGPoint) {
    ...
}

您还需要另一个单独的函数来处理计时器参数(更多信息请参见此处:):

func spawnBullets(sender: Timer) {
    if let location = sender.userInfo as! CGPoint? {
        spawnBullets(location)
    }
}

你的 touchBegan 最终会是这样的:

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

        let location = touch.location(in: self)
        spawnBullets(location)
        Timer.scheduledTimer(
            timeInterval: 0.2, 
            target: self,
            selector:#selector(spawnBullets(sender:)),
            userInfo: location,
            repeats: true
        )

    }
}