ios - SKNode帧不正确?

标签 ios swift sprite-kit skshapenode

这是我的 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/

相关文章:

ios - 如何从按钮集合中找到位置?

ios - 获取以编程方式添加的 id 步进器

ios - 无法使具有标识符 cellID 的单元格出队。相同的代码在旧的 Swift 上运行良好

ios - ShareKit 是否仍然有效 - 2015?如果可以,是否可以在 Swift 中实现?

swift - 交互时删除节点 Spritekit

ios - Charles 代理 100% 节流

iphone - 更新应用程序时出现代码签名错误

swift - 将子字符串与 Swift 中的另一个子字符串匹配

swift - Xcode SpriteKit 调用中的额外参数 'forReadingWithData"

swift - 如何防止使用触摸位置处理的 SKShapeNode 超出圆形路径?