Paul Michaels
Paul Michaels

Reputation: 16685

Determine the width of an SKPhysicsBody in Swift

I have the following code to set-up a new PhysicsBody:

let size = CGSize(width: 100, height: 10)

let player = SKShapeNode(rectOf: size)
player.lineWidth = 1

player.physicsBody = SKPhysicsBody(rectangleOf: size)

player.physicsBody?.affectedByGravity = false
player.physicsBody?.isDynamic = true

When the user touched the screen, I'm trying to determine whether they have touched inside the object, to the left, or to the right:

func touchDown(atPoint pos : CGPoint) {
    if (pos.x <= (player?.position.x)!) {
        // left
    } else if (pos.x >= (player?.position.x)! + (player?.frame.width)!) {
        // right
    } else {

        print(player?.position.x)
        print ((player?.position.x)! + (player?.frame.width)!)
        print(pos.x)
        // middle
    }
}

What the debug statements, and my experimenting are telling me, is that the player?.frame.width is not returning the correct width for the object. But, more than that, I seem to be returning a centre even when the object is way off. The object is moving, and so I suspect the issue is that it's returning a previous position.

So, I have a two part question: is frame.width the correct way to determine the width, and is there something that could be causing this apparent lag of information when using the touchesBegan event?

Upvotes: 2

Views: 80

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

position is dependent on the anchorPoint, which is usually (0.5,0.5) or the center of the sprite.

position is also relative to the parent, so you need to make sure you are using the correct coordinate system, your best option would be touch.location(in:player) to get the touch in the coordinate system of player.

After you got that going, when x is negative you know it is left and when x is positive, you know it is right. Also when -width/2 < x < width/2, you know you are inside the node, where 0 means you hit dead center.

Upvotes: 2

Related Questions