SpriteKit创建按钮点击无响应 无法触发玩家跳跃动作问题求助
问题排查&修复方案
故障原因
touchesBegan方法定义在didMove(to:)方法内部,属于局部函数,未作为GameScene的实例方法实现,系统无法触发触摸回调touchesBegan缺少override关键字,方法签名不符合SpriteKit的系统回调要求player、button是didMove(to:)内的局部变量,触摸方法无法跨作用域访问
修正后完整代码
import SwiftUI import SpriteKit import UIKit class GameScene: SKScene { // 将player、button提升为类成员属性 let button = SKSpriteNode(imageNamed: "playerOBJ") let player = SKSpriteNode(imageNamed: "playerOBJ") override func didMove(to view: SKView) { let playerRadius = player.frame.width / 2.0 player.position = CGPoint(x: 200, y: 500) player.name = "Jimmy" addChild(player) player.physicsBody = SKPhysicsBody(circleOfRadius: playerRadius) player.physicsBody?.allowsRotation = false player.physicsBody?.friction = 0 player.physicsBody?.restitution = 0 player.zPosition = 100 // Button button.name = "btn" button.size.height = 100 button.size.width = 100 button.position = CGPoint(x: 100, y: 100) self.addChild(button) // Physics physicsBody = SKPhysicsBody(edgeLoopFrom: frame.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))) Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in self?.player.physicsBody?.applyForce(CGVector(dx: 100, dy: 1000)) } } // 把touchesBegan移到类作用域,使用正确的方法签名 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first guard let positionInScene = touch?.location(in: self) else { return } let touchedNode = self.atPoint(positionInScene) if let name = touchedNode.name, name == "btn" { player.physicsBody?.applyForce(CGVector(dx: 0, dy: 10000)) } } override func update(_ currentTime: TimeInterval) { } }
内容的提问来源于stack exchange,提问作者Superbia
相关产品推荐
相关产品推荐

