【发布时间】:2014-06-05 09:43:43
【问题描述】:
我很难发现为什么我无法使用 SpriteKit 检测到 bodyAtPoint。 bodyAtPoint 总是返回 nil,即使它看起来我总是在点击精灵节点。
代码如下:
...
let spaceship = SKSpriteNode(color: UIColor.blueColor(), size: CGSizeMake(100, 100))
override func didMoveToView(view: SKView) {
/* Setup your scene here */
var borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
self.physicsBody = borderBody
self.physicsBody.friction = 0.0
self.physicsWorld.gravity = CGVectorMake(0.0, 0.0)
spaceship.name = "spaceship"
spaceship.position = CGPointMake(400, 300)
var bodySize = CGSizeMake(spaceship.size.width / 1.15, spaceship.size.height / 1.15);
spaceship.physicsBody = SKPhysicsBody(rectangleOfSize: bodySize)
spaceship.physicsBody.dynamic = false
spaceship.physicsBody.restitution = 1.0
spaceship.physicsBody.friction = 0.0
spaceship.physicsBody.linearDamping = 0.0
spaceship.physicsBody.allowsRotation = false
self.addChild(spaceship)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
super.touchesBegan(touches, withEvent: event)
var touch : UITouch! = touches.anyObject() as UITouch
var touchLocation : CGPoint! = touch.locationInNode(self)
if self.physicsWorld.bodyAtPoint(touchLocation) {
NSLog("true")
} else {
NSLog("false")
}
}
...
结果:
spaceship.physicsBody 输出:
<SKPhysicsBody> type:<Rectangle> representedObject:[<SKSpriteNode> name:'spaceship' texture:['nil'] position:{400, 300} size:{100, 100} rotation:0.00]
touchLocation 输出:
(411.943664550781,553.014099121094)
self.physicsWorld.bodyAtPoint(touchLocation) 总是:
nil
...因此条件总是返回false。
谁能解释我哪里出错了?我想最终检测到精灵节点上的触摸并执行操作。
编辑:
即使我简化为以下内容,我仍然总是得到false:
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
...
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.physicsWorld.bodyAtPoint(location) {
NSLog("true")
} else {
NSLog("false")
}
}
}
...
【问题讨论】:
-
SpriteKit 是从左上角使用原点还是需要将其还原为左下角?
-
@eXhausted 很抱歉,但我不确定...
-
还有一种方法叫做
self.physicsWorld.bodyInRect,如果你是从SKNode继承的,请尝试调用self.physicsWorld.bodyInRect(self.frame)。它会返回一些值吗? -
也可以使用:
let location = touch.locationInNode(self) let nodeAtPoint = self.nodeAtPoint(location) println("NODE AT POINT: \(nodeAtPoint)") -
@eXhausted 非常感谢!我已经用答案更新了帖子。
标签: ios sprite-kit swift