[英]SpriteKit PhysicsBody non-rectangular collision
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
在這個編碼中我使用了rectangleOfSize
作為碰撞物理體,但是如果我想按像素使用圖像的形狀,我應該使用什么而不是rectangleOfSize
?
你應該做一個CGPath
這是你的物體的形狀,並使用SKPhysicsBody
的init(polygonFromPath path: CGPath)
如這里所描述
您可以根據紋理創建物理實體:
pipeUp.physicsBody = SKPhysicsBody(texture:pipeUp.texture)
它將為您創建一個alpha蒙版紋理,因此任何具有alpha 0的像素都不會包含在物理實體中。
編輯:
@classenApps讓我意識到我做了一個擴展來做這個,所以我會添加它的答案是正確的。
extension SKPhysicsBody
{
convenience init(texture: SKTexture)
self.init(texture:texture,size:texture.size())
}
我會使用KnightOfDragon的方法添加size
:參數,如下所示:
pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, size: pipeUp.size)
我相信使用CGPath
存在/曾經是內存泄漏。
如果您需要明確告訴紋理使用哪個alphaThreshold,另一個解決方案可以是:
/**
Creates a body from the alpha values in the supplied texture.
@param texture the texture to be interpreted
@param alphaThreshold the alpha value above which a pixel is interpreted as opaque
@param size of the generated physics body
*/
@available(iOS 8.0, *)
public /*not inherited*/ init(texture: SKTexture, alphaThreshold: Float, size: CGSize)
所以代碼將是:
pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, alphaThreshold: 0.3, size: pipeUp.size)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.