Bohdan Kovalenko
Bohdan Kovalenko

Reputation: 41

Use PhysicsBody with SKShapenode line. Swift, iOS, SpriteKit

I need to add simple line using ShapeBody to interact with. I'am trying code below, by Xcode gives me next response:

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)

Upvotes: 2

Views: 1056

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16827

A path cannot intersect any of its lines with a SKPhysicsBody, your line needs to be a thin rectangle

    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)

Upvotes: 1

Bohdan Kovalenko
Bohdan Kovalenko

Reputation: 41

Used edgeChainFrom instead of polygonFrom, and it works!

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

Upvotes: 2

Related Questions