0
votes

If I create an SKPhysicsBody and add it to an SKSpriteNode as below then the collision detection works fine with the floor object below.

let myObjectBody = SKPhysicsBody(circleOfRadius: 100)

However, if instead I create the PhysicsBody using the texture of the SKSpriteNode to which it is applied then the collision doesn't work. Although it does register contact, the object just falls through the floor.

let myObjectBody = SKPhysicsBody(texture: myObject.texture!, alphaThreshold: 0, size: myObject.texture!.size())

Important note: If I set show physics to true:

skView.showsPhysics = true

Then the physics outline matches perfectly the outline of the shape of the sprite, which is generated from a png.

The physicsBody is added to the object and then the scene in the following manner.

let myTexture = SKTexture(imageNamed: "myImage")
let myObject = SKSpriteNode(texture: myTexture)
myObject.xScale = 0.2
myObject.yScale = 0.2 //The image is big to allow zooming

let myObjectBody = SKPhysicsBody(texture: myObject.texture!, alphaThreshold: 0, size: myObject.texture!.size())

myObject.physicsBody = myObjectBody
myWorld.addChild(myObject)
2
Can you provide info how you adding SKPhysicsBody to your scene?Alexey Bondarchuk
Hi, but I still can't see from where do you get myObject? What kind of class this is and how do you init it?Alexey Bondarchuk

2 Answers

0
votes

Okay, I figured out how to make this work.

I was confused by the showsPhysics property. I needed to set the size of the physics object to be the same scale as the image.

So, this works:

    let myObjectSize = CGSize(width: myObject.texture!.size().width * 0.2, height: myObject.texture!.size().height * 0.2)
    let leafBody = SKPhysicsBody(texture: myObject.texture!, alphaThreshold: 0, size: myObjectSize)

This seems natural but what threw me off is that the visualised (blue) physicsBody when showsPhysics is turned on is five times smaller than the effect it is producing. So the blue shape of the image is inside the actual image (a mini version). The code in my question above created a nice blue visualised physicsBody that seemingly matched the image but in reality it was far too big.

0
votes

This is a problem with the simulator. Either downgrading to iOS 12.x or using a physical device seems to fix the problem.