SKShapeNode 似乎缺少触摸
SKShapeNode seems to be missing touches
我想知道是否有好心的专家可以帮助我解决初学者的问题。我想使用 SKShapeNodes 来表示非矩形形状,但需要检测对它们的触摸。
我下面的代码似乎不起作用。我是否遗漏了一些微不足道的东西?
import SpriteKit
class GameScene: SKScene , SKPhysicsContactDelegate {
var ball: SKShapeNode!
override func didMove(to view: SKView) {
backgroundColor = .white
ball = createBall()
ball.position = CGPoint.zero
addChild(ball)
}
func createBall() -> SKShapeNode {
let path = CGMutablePath()
path.addArc(center: CGPoint.zero,
radius: 35,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true)
let ball = SKShapeNode(path: path, centered: true)
ball.lineWidth = 1
ball.fillColor = .lightGray
ball.strokeColor = .black
ball.isUserInteractionEnabled = true
return ball
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
print("\(location)") // diagnostic - produces output whenever click is NOT within SKShapeNode
if ball.contains(location) {
print("\(location)") // diagnostic - never produces output!!
}
}
}
}
删除以下代码行:-
ball.isUserInteractionEnabled = true
它对我来说很好用。
我想知道是否有好心的专家可以帮助我解决初学者的问题。我想使用 SKShapeNodes 来表示非矩形形状,但需要检测对它们的触摸。
我下面的代码似乎不起作用。我是否遗漏了一些微不足道的东西?
import SpriteKit
class GameScene: SKScene , SKPhysicsContactDelegate {
var ball: SKShapeNode!
override func didMove(to view: SKView) {
backgroundColor = .white
ball = createBall()
ball.position = CGPoint.zero
addChild(ball)
}
func createBall() -> SKShapeNode {
let path = CGMutablePath()
path.addArc(center: CGPoint.zero,
radius: 35,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: true)
let ball = SKShapeNode(path: path, centered: true)
ball.lineWidth = 1
ball.fillColor = .lightGray
ball.strokeColor = .black
ball.isUserInteractionEnabled = true
return ball
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in: self)
print("\(location)") // diagnostic - produces output whenever click is NOT within SKShapeNode
if ball.contains(location) {
print("\(location)") // diagnostic - never produces output!!
}
}
}
}
删除以下代码行:-
ball.isUserInteractionEnabled = true
它对我来说很好用。