将 PhysicsBody 与 SKShapenode 线一起使用。 Swift, iOS, SpriteKit

Use PhysicsBody with SKShapenode line. Swift, iOS, SpriteKit

我需要使用 ShapeBody 添加简单的线条来与之交互。 我正在尝试下面的代码,Xcode 给我下一个回复:

PhysicsBody: Could not create physics body.

        let testPath = UIBezierPath()
        testPath.move(to: CGPoint(x:-100, y: 200))
        testPath.addLine(to: CGPoint(x:100, y: 200))

        let testShape = SKShapeNode()
        testShape.path = testPath.cgPath
        testShape.position = CGPoint(x:0, y:250)
        testShape.zPosition = 5
        testShape.lineWidth = 5
        testShape.strokeColor = .red
        testShape.physicsBody = SKPhysicsBody(polygonFrom: testPath.cgPath)

使用 edgeChainFrom 而不是 polygonFrom,而且有效!

testShape.physicsBody = SKPhysicsBody(edgeChainFrom: testPath.cgPath)

路径不能与它的任何线相交 SKPhysicsBody,你的线需要是一个细矩形

    let testPath = UIBezierPath()
    testPath.move(to: CGPoint(x:-100, y: 200))
    testPath.addLine(to: CGPoint(x:100, y: 200))
    testPath.addLine(to: CGPoint(x:100, y: 201))
    testPath.addLine(to: CGPoint(x:-100, y: 201))
    testPath.close()
    let testShape = SKShapeNode()
    testShape.path = testPath.cgPath
    testShape.position = CGPoint(x:0, y:250)
    testShape.zPosition = 5
    testShape.lineWidth = 5
    testShape.strokeColor = .red
    testShape.physicsBody = SKPhysicsBody(polygonFrom: testPath.cgPath)