【问题标题】:SpriteKit PhysicsBody non-rectangular collisionSpriteKit PhysicsBody 非矩形碰撞
【发布时间】:2016-07-18 12:36:02
【问题描述】:
    pipeUp.physicsBody = SKPhysicsBody(rectangleOfSize: pipeUp.size)

在这个编码中,我使用rectangleOfSize 来表示碰撞物理体,但如果我只想按像素使用图像的形状,我应该使用什么来代替rectangleOfSize

【问题讨论】:

  • 请注意,didBeginContact 会触发多次,因为它们是多个接触点,您必须在代码中处理此问题

标签: ios xcode sprite-kit swift2


【解决方案1】:

你应该创建一个CGPath,这是你的对象的形状,并使用SKPhysicsBodyinit(polygonFromPath path: CGPath)作为described here

【讨论】:

    【解决方案2】:

    我会使用 KnightOfDragon 的方法并添加 size: 参数,如下所示:

    pipeUp.physicsBody = SKPhysicsBody(texture: pipeUp.texture, size: pipeUp.size)
    

    我相信使用CGPath 存在/曾经存在内存泄漏。

    【讨论】:

    • 实际上,你的方式就是这样做的方式,基于 AppleDocs,我有一个扩展,它没有大小
    【解决方案3】:

    如果您需要明确告诉纹理使用什么 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)
    

    【讨论】:

      【解决方案4】:

      您可以根据纹理创建物理体:

      pipeUp.physicsBody = SKPhysicsBody(texture:pipeUp.texture)  
      

      它将为您创建一个 alpha 蒙版纹理,因此任何具有 alpha 0 的像素都不会包含在物理体中。

      编辑:

      @classenApps 让我意识到我为此做了一个扩展,所以我会添加它以确保答案正确。

      extension SKPhysicsBody
      {
          convenience init(texture: SKTexture)
          self.init(texture:texture,size:texture.size())
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多