本文介绍了碰撞检查问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该代码检查用户是否轻拍了与随机改变纹理的球具有相同纹理的球.但是在我的控制台中,尽管我轻点与随机改变纹理的球具有相同纹理的球,但点"仅偶尔打印.如何解决这个问题.这与向其他球添加PhysicalBody有关吗?
The code checks if the user taps a ball with the same texture as a ball that randomly changes textures. But in my console "Point" is only printed occasionally although I tap on the ball with the same texture as the ball that randomly changes texture. How can this be fixed. Has this something to do with adding a physicsBody to the other balls?
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var array = [blueTexture, redTexture, greenTexture, yellowTexture]// var with value of textures
var blackB = childNodeWithName("changeBall") as! SKSpriteNode
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
blackB.texture = array[randomIndex] // blackB is given a random texture
for t in touches { // check each touch
let touch = t as! UITouch
let pos = touch.locationInNode(self) // find touch position
for child in self.children { // check each children in scene
if let ball = child as? SKSpriteNode{
if ball !== blackB && ball.containsPoint(pos) { // check for collision, but skip if it's a blackB
if ball.texture == blackB.texture { // collision found, check color
println("POINT")
}
}
}
}
}
}
推荐答案
一些观察结果...
-
nodeAtPoint(pos)
可以替换子节点上的for
循环 不需要 -
ball.containsPoint(pos)
,因为nodeAtPoint
执行相同的测试 -
ball !== blackB
应该是ball != blackB
- 也许在检查纹理匹配后更改为随机纹理更有意义
nodeAtPoint(pos)
can replace thefor
loop over child nodesball.containsPoint(pos)
is not needed becausenodeAtPoint
performs the same testball !== blackB
should beball != blackB
- Perhaps changing to a random texture after checking for a texture match makes more sense
具有上述更改的实现
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
var array = [blueTexture, redTexture, greenTexture, yellowTexture]
var blackB = childNodeWithName("changeBall") as! SKSpriteNode
if let touch = touches.first as? UITouch {
let pos = touch.locationInNode(self)
if let ball = nodeAtPoint(pos) as? SKSpriteNode {
if ball != blackB && ball.texture == blackB.texture {
println("POINT")
}
}
}
// Change texture after checking for a texture match
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
blackB.texture = array[randomIndex]
}
这篇关于碰撞检查问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!