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

Swift开发iOS应用:mouseDown事件位置检测报错求助

解决SpriteKit中mouseDown事件获取位置的错误

错误原因

iOS中的UIEvent类没有location(in:)方法,这个方法是macOS平台NSEvent类的API。在iOS上,需要通过UIEvent包含的UITouch对象来获取触摸/点击位置。另外你代码里每次触发mouseDown都重新初始化GameScene,这会导致你操作的不是当前屏幕上显示的场景实例,逻辑完全错误。

修正方案

  • 从UIEvent中提取对应的UITouch对象,通过UITouch的location(in:)方法获取位置
  • 获取当前ViewController正在展示的GameScene实例,而非重新创建

修正后的代码

import SpriteKit

extension GameViewController {
    func mouseDown(with event: UIEvent) {
        // 获取当前触摸对象,同时拿到当前显示的SKView和GameScene
        guard let touch = event.allTouches?.first,
              let skView = view as? SKView,
              let ourScene = skView.scene as? GameScene else {
            return
        }
        
        // 直接获取点击位置在GameScene坐标系中的坐标
        let location = touch.location(in: ourScene)
        let node = ourScene.atPoint(location)
        
        if node.name == "creditsInfo" {
            showCredits()
        }
    }
}

补充说明

  • 把view强转为SKView是因为SpriteKit应用的ViewController通常以SKView作为根视图
  • 用touch.location(in: ourScene)直接获取场景内的坐标,无需额外做坐标转换
  • 使用guard语句提前退出,比嵌套if let的代码结构更简洁易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:12:09