[英]SpriteKit PhysicsBody non-rectangular collision
pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)
在这个编码中我使用了rectangleOfSize
作为碰撞物理体,但是如果我想按像素使用图像的形状,我应该使用什么而不是rectangleOfSize
?
你应该做一个CGPath
这是你的物体的形状,并使用SKPhysicsBody
的init(polygonFromPath path: CGPath)
如这里所描述
You can create a physics body based on the texture: 您可以根据纹理创建物理实体:
pipeUp.physicsBody = SKPhysicsBody(texture:pipeUp.texture)
It will create an alpha mask texture for you, so any pixel that has an alpha 0, will not be included in the physics body. 它将为您创建一个alpha蒙版纹理,因此任何具有alpha 0的像素都不会包含在物理实体中。
Edit: 编辑:
@classenApps made me realize I made an extension to do this, so I will add it for the answer to be correct. @classenApps让我意识到我做了一个扩展来做这个,所以我会添加它的答案是正确的。
extension SKPhysicsBody
{
convenience init(texture: SKTexture)
self.init(texture:texture,size:texture.size())
}
I'd use KnightOfDragon's method with the addition of the size
: parameter like this: 我会使用KnightOfDragon的方法添加
size
:参数,如下所示:
pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, size: pipeUp.size)
I believe there is/used to be a memory leak using the CGPath
. 我相信使用
CGPath
存在/曾经是内存泄漏。
If you need to explicitly tell the texture what alphaThreshold to use, another solution can be: 如果您需要明确告诉纹理使用哪个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)
So the code will be: 所以代码将是:
pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, alphaThreshold: 0.3, size: pipeUp.size)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.