This is the constructor for my NumberTile
class:
class NumberTile: SKShapeNode {
var tileColorArray = NSArray(objects: "#996666","#a65959","#b34d4d","#bf4040","#cc3333","#d92626","#e61919") //red
init(xPos: NSInteger, yPos: NSInteger) {
super.init()
let size = CGSize(width: 40, height: 40)
self.path = CGPathCreateWithRect(CGRect(origin: CGPointZero, size:size), nil)
self.position = CGPointMake(0, (CGFloat)(yPos))
let fillColor = UIColor(rgba: tileColorArray.objectAtIndex(Int(arc4random_uniform(UInt32(self.tileColorArray.count)))) as! String)
self.fillColor = fillColor
self.strokeColor = UIColor.blackColor()
self.physicsBody = SKPhysicsBody(rectangleOfSize: self.frame.size, center: CGPointMake((CGFloat)(GlobalConstants.k_TILE_SIZE/2),(CGFloat)(GlobalConstants.k_TILE_SIZE/2)))
self.physicsBody?.mass = GlobalConstants.k_TILE_MASS
self.physicsBody?.friction = 1.0
self.physicsBody?.allowsRotation = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I have hard-coded the size to be 40 x 40 and the x-position to be 0.
I add NumberTile
s to the scene with the following code:
let tile = NumberTile(xPos: xPos, yPos: yPos)
print("tile position: \(NSStringFromCGRect(tile.frame)) xPos:\(xPos)")
print("physic body: \(tile.physicsBody)")
addChild(tile)
xPos
can be ignored as I hardcoded it in the constructor for debugging.
The result is:
tile position: {{-0.5, 373.5}, {41, 41}} xPos:0
physic body: Optional(<SKPhysicsBody> type:<Rectangle> representedObject:[<SKShapeNode> name:'(null)' accumulatedFrame:{{-0.5, 373.5}, {41, 41}}])
Why has the xPos
been shifted by -0.5
and the width and height have been increased by 1?
Update
For the xPos
, I have finally figured it out. In the constructor, I should set the origin to (0.5, 0.5)
as follows:
self.path = CGPathCreateWithRect(CGRect(origin: CGPointMake(0.5, 0.5), size: size), nil)
But I still have no idea why the width and height are being increased by 1.
I believe that stroking the path will will increase the shape by the size of the stroke (which I am guessing is
0.5
on each side) That is what is giving you the0.5
offset and the+1
to the size. Either inset your rect by one to account for it or don't set a stroke color