这是我的 NumberTile
类的构造函数:
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")
}
}
我已将尺寸硬编码为 40 x 40,将 x 位置硬编码为 0。
我使用以下代码将 NumberTile
添加到场景中:
let tile = NumberTile(xPos: xPos, yPos: yPos)
print("tile position: \(NSStringFromCGRect(tile.frame)) xPos:\(xPos)")
print("physic body: \(tile.physicsBody)")
addChild(tile)
xPos
可以忽略,因为我在构造函数中对其进行了硬编码以进行调试。
结果是:
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}}])
为什么xPos
移动了-0.5
并且宽度和高度增加了1?
更新
对于xPos
,我终于想通了。在构造函数中,我应该将原点设置为 (0.5, 0.5)
,如下所示:
self.path = CGPathCreateWithRect(CGRect(origin: CGPointMake(0.5, 0.5), size: size), nil)
但是我还是不明白为什么宽度和高度要增加1。
最佳答案
我相信抚摸路径会增加笔划大小的形状(我猜每边是 0.5
),这就是给你 0.5
偏移量和大小的 +1
。要么将你的矩形插入一以解释它,要么不设置描边颜色
关于ios - SKNode帧不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31043058/