使用Swift和SpriteKit时:SKPhysicsBody(polygonFromPath:CGPath)出现问题

使用Swift和SpriteKit时:SKPhysicsBody(polygonFromPath:CGPath)出现问题,swift,sprite-kit,skspritenode,skphysicsbody,cgpath,Swift,Sprite Kit,Skspritenode,Skphysicsbody,Cgpath,我正在尝试为一个SKSpriteNode创建一个物理体。我通常使用图像创建物理体,并说: snode = SKSpriteNode(imageNamed: snodeImage) snode = SKPhysicsBody(texture: snode.texture!, size: snode.size) 我希望能够使用以下方法创建物理实体: snode.physicsBody = SKPhysicsBody(polygonFromPath: CGPath) 我不知道如何做到这一点,我已经

我正在尝试为一个SKSpriteNode创建一个物理体。我通常使用图像创建物理体,并说:

snode = SKSpriteNode(imageNamed: snodeImage)
snode = SKPhysicsBody(texture: snode.texture!, size: snode.size)
我希望能够使用以下方法创建物理实体:

snode.physicsBody = SKPhysicsBody(polygonFromPath: CGPath)

我不知道如何做到这一点,我已经尝试在网上寻找,但我不能找出它。谁能给我举个小例子吗?也许可以告诉我如何使用此构造函数创建一个简单的矩形物理体?

最简单的方法是使用
UIBezierPath
,因为它有许多有用的构造函数,然后将其转换为
polygonFromPath
想要的
CGPath

您需要一些代码来创建一个简单的矩形物理体:

let square = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 128, height: 128))
square.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))

let path = UIBezierPath(rect: CGRect(x: -64, y: -64, width: 128, height: 128))
square.physicsBody = SKPhysicsBody(polygonFromPath: path.CGPath)

addChild(square)
请注意,物理实体是偏移的,因为它是从其节点的中心测量的。您可能希望在GameViewController.swift文件中使用
skView.showsPhysics=true
,以帮助调试物理图形