在xcode中使用选择器swift
问题描述:
今天我的编码遇到了一些麻烦。试图制作一个“自动”武器,但无法让选择器正常工作。 下面是代码在xcode中使用选择器swift
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版本。迅速3.x有一些小的变化。
在迅速3.X你不使用引号选择以这种方式,所以你必须删除引号&做这样的事情:
selector:#selector(spawnBullets)
这也给你某种类型的安全性时,改变你的代码。所以,如果你做错了某些事情,你会得到编译时错误,而不是运行时错误。
我也会在你的情况做的是移动的功能spawnBullets touchBegan外面是这样的:
func spawnBullets(_ location: CGPoint) {
...
}
您还需要另一个单独的FUNC处理定时器参数(更多信息在这里:https://stackoverflow.com/a/41987413/404659 ):
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
)
}
}
目标/动作的选择器必须在类的顶层,“let location = ...'这一行是疯狂的。 – vadian
是的。但是当我复制代码时这只是一个错误 –