I have created a SKShapeNode
in the following way,
let sprite = SKShapeNode(rect: CGRect(x: -20, y: -10, width: 40, height: 20), cornerRadius: 10)
I also set a physics body like so,
sprite.physicsBody = SKPhysicsBody(rectangleOf: sprite.frame.size)
but I realized that the collisions and contacts weren't precise, so I changed showsPhysics
to true
and got the following. How can I make the physics body precise, even for the rounded corners?
Remember that too much precision is very bad for performance. Read this: https://developer.apple.com/reference/spritekit/skphysicsbody
For general cases, it would be better to ignore the corners and stick with the normal rectangle physics, unless you REALLY need that precision. If you do, you could use a SKTexture on a SKSpriteNode instead of a ShapeNode. That would be much easier, because you could simply do this:
With a texture, you can easily make a more detailed and precise physicsBody by simply using the
SKPhysicsBody(texture: size:)
constructor.I would follow the documentation of SKPhysicsBody, and create a polygonal shape that approximates the rounded corners of your sprite.
An example on the documentation shows that you can define a polygonal physics body like so:
From the documentation:
Maybe the #4 is your case
Spaceship 1: circular physics body
Spaceship 2: rectangular physics body
Spaceship 3: polygonal physics body
Spaceship 4: physics body using texture’s alpha channel