Search code examples
iosswiftsprite-kitsknode

SKShapeNode position line up with ground


I am simply trying to draw a rectangle and placing it in the bottom left hand side of the screen

    var rectW:CGFloat  = CGFloat(200.0)
    var rectH:CGFloat = ceil(self.frame.height * 0.15)

    var rect = SKShapeNode(rectOfSize: CGSize(width: rectW, height: rectH));

    let posX:CGFloat = 0.0 + (rect.frame.width / 2)
    let posY:CGFloat = self.frame.height - (self.frame.height - rect.frame.height)

    rect.position = CGPointMake(posX,posY)
    rect.fillColor = SKColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
    rect.lineWidth = 1

    self.addChild(rect)

The issue is that even though i believe all the maths is correct the rectangle is about 38 points/pixels that are under the screen, as you can see from the image below (the white border shows the limit).

For your information here is an output of the positions, heights and widths.

PosX: 100.5
PosY: 117.0
Rect Width: 201.0
Rect Height: 117.0
Frame Height: 768.0
Frame Weight: 1024.0

Rectangle under the screen

If i simple take this line but add 38 points/pixels it works, but why? Is there something I am missing?

    let posY:CGFloat = self.frame.height - (self.frame.height - rect.frame.height) + 38

Rectangle in correct position


Solution

  • I found the answer via the following two answers:

    SpriteKit coordinate system messed up

    Problems understanding coordinate system SpriteKit using Swift

    The problem turns out to be with GameScene.sks having it's size set differently.

    Open up GameScene.sks and go to 'Show SKNodeInspector' should be the third box in the top right hand side of the screen.

    Then set the dimensions to 320 x 568

    Save then run. Should be working.