Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, SpriteKit: Position Of Physic Body Wrong For SpriteNode When Using edgeLoopFromRect

I am trying to create a physics body for a sprite node which is only for the outline of the sprite node. For this, I tried to use edgeLoopFromRect. However, when i try this, the physics body doesn't match the position of the sprite node. For example, the sprite node would be in the centre of the screen, and its physics body would be in the top corner of the screen (see pic - the outline of the physics body is only showing the corner, as some is off the screen). I want to use this to create the outline of a game area, which will act as a boarder for the object to make contact with for game over.

Screen Shot

Here's my code:

//Physic Body Outline Test

    let screenS = SKSpriteNode(imageNamed: "TestImage")
    screenS.size = CGSize(width: 100, height: 100)
    screenS.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
    screenS.physicsBody = SKPhysicsBody(edgeLoopFrom: screenS.frame)
    screenS.physicsBody!.affectedByGravity = false
    self.addChild(screenS)

Why is the position so far off? What am I doing wrong? Is this even the correct approach to setting up an physic body outline for a game area?

Thanks! :D

like image 336
HeanMachine Avatar asked Sep 06 '25 18:09

HeanMachine


1 Answers

Just move the line setting the sprite's position to be after the defining the physicsBody - there seems to be a bug in SpriteKit concerning this. You should end up with:

screenS.physicsBody = SKPhysicsBody(edgeLoopFrom: screenS.frame)
screenS.position = CGPoint(x: self.size.width/2, y: self.size.height/2)

It's still a bit odd to use an edgeLoop as the physicsBody for a sprite - SK will think the sprite has no mass etc and any physics interactions won't work as expected.

like image 164
Steve Ives Avatar answered Sep 11 '25 06:09

Steve Ives