斯威夫特|检测到碰撞时忽略精灵的透明部分?

时间:2015-04-29 08:19:55

标签: swift transparency transparent ignore collision

除了透明部分之外,我想检测精灵的每个部分的碰撞。我找到了C的解决方案,但我无法弄清楚如何在swift中做到这一点。

这是Obj-C解决方案: sprite kit collisions: ignore transparency?

有人有任何想法吗?

编辑:

这是我构建形状的功能代码。我不确定如何将spriteName.physicsBody设置为其他用户提供的答案。

func addTriangles() {


    center = SKSpriteNode(imageNamed:"images/center.png")
    center.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
    center.zPosition = -1
    center.physicsBody = init!(texture centerTexture: SKTexture!, size 1.0: CGSize) -> SKPhysicsBody?
    center.physicsBody?.dynamic = false
    center.physicsBody?.affectedByGravity = false
    center.physicsBody?.categoryBitMask = PhysicsCategory.Triangle
    self.addChild(center)
    spin = clockwise
    center.runAction(SKAction.repeatActionForever(spin))


}

2 个答案:

答案 0 :(得分:1)

你实际上可以使用

init!(texture texture: SKTexture!, size size: CGSize) -> SKPhysicsBody? 

使用精灵纹理的alpha通道设置碰撞体

但是,不建议这样做,因为模拟复杂形状的物理行为会花费很多。

如果您有一个形状复杂的精灵,请尝试绘制另一个更简单的形状,并将其纹理用作物理身体。

答案 1 :(得分:0)

为物理体绘制一个单独的更简化的图像(从颜色和几何角度来看)绝对是个好主意,对于代码来说,它与你需要的非常接近:

let birdMask: UInt32 = 0x1 << 0
let pipeMask: UInt32 = 0x1 << 1
//...

pipeImage = SKSpriteNode(imageNamed: "realImage")
//... size and position

let maskTexture = SKSpriteNode(imageNamed: mask)
maskTexture.size = pipeImage!.size // size of texture w/ real imageNamed

pipeImage!.physicsBody?.usesPreciseCollisionDetection = true
pipeImage!.physicsBody = SKPhysicsBody(texture: maskTexture.texture!, size: size)        
pipeImage!.physicsBody?.affectedByGravity = false // disable falling down...
pipeImage!.physicsBody?.allowsRotation = false
pipeImage!.physicsBody?.isDynamic = true
pipeImage!.physicsBody?.friction = 0
pipeImage!.physicsBody?.categoryBitMask = pipeMask
pipeImage!.physicsBody?.collisionBitMask = birdMask | pipeMask
pipeImage!.physicsBody?.contactTestBitMask = birdMask | pipeMask

这是full guide how使其成为