You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中实现按住屏幕持续发射子弹的问题求助

搞定按住屏幕持续发射子弹的问题!

看你的代码,已经能创建并发射单颗子弹了,但缺少按住屏幕时重复触发发射动作的逻辑,这就是为啥没法连续发射的原因。下面给你完整的实现方案:

第一步:先加个定时器变量

在你的SKScene类里定义一个定时器,用来控制重复发射的节奏:

var fireTimer: Timer?

第二步:处理“按住屏幕”的事件

当用户按下屏幕时,启动定时器,每隔一小段时间就调用一次你的fireBullet()函数:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // 防止重复点按启动多个定时器
    guard fireTimer == nil else { return }
    // 这里设0.1秒发射一次,你可以根据游戏手感调整这个间隔
    fireTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(fireBullet), userInfo: nil, repeats: true)
}

第三步:处理“松开屏幕”的事件

当用户松手或者触摸被打断(比如来电)时,要立刻停止定时器,不然子弹会一直发射:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    fireTimer?.invalidate()
    fireTimer = nil
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    // 触摸被取消时也调用停止逻辑,比如突然弹出通知
    touchesEnded(touches, with: event)
}

第四步:补全你的fireBullet函数

你原来的代码里physicsBody的设置没写完,我帮你补上必要的配置,比如子弹的速度和碰撞掩码:

@objc func fireBullet() {
    let bullet = SKSpriteNode(imageNamed: "bullet")
    bullet.name = "Bullet"
    bullet.setScale(1.5)
    bullet.position = player.position
    bullet.zPosition = 1
    
    bullet.physicsBody = SKPhysicsBody(rectangleOf: bullet.size)
    bullet.physicsBody!.affectedByGravity = false
    bullet.physicsBody!.categoryBitMask = PhysicsCategories.Bullet
    // 这里根据你的游戏需求设置碰撞和接触检测的掩码
    bullet.physicsBody!.collisionBitMask = PhysicsCategories.Enemy
    bullet.physicsBody!.contactTestBitMask = PhysicsCategories.Enemy
    
    // 给子弹一个飞行速度,比如向上发射(dy值可以调整快慢)
    bullet.physicsBody!.velocity = CGVector(dx: 0, dy: 500)
    
    addChild(bullet)
    
    // 可选:子弹飞出屏幕后自动移除,避免占用内存
    let cleanUpAction = SKAction.sequence([
        SKAction.wait(forDuration: 2),
        SKAction.removeFromParent()
    ])
    bullet.run(cleanUpAction)
}

几个小提醒

  • 记得一定要在松手时停止定时器,不然就算玩家松开了,子弹还会不停发射
  • 定时器的时间间隔(0.1秒)可以反复调试,找到最适合你游戏的射速
  • 如果你的游戏是用手势识别器处理触摸,逻辑也是一样的:按住时启动定时器,松手时停止

内容的提问来源于stack exchange,提问作者user9459145

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:32:28