sknode can't see added children

徘徊边缘 提交于 2019-12-13 01:26:24

问题


Here i created a menu class which contains a few items. I want to display these sprites in the main class. I experimented with this by creating an object associating with the sknode class in the touches began method, but when i added the menu object in the main class using the addChild thing, nothing showed up.

class menu:SKNode {
    let background = SKSpriteNode(imageNamed:"background") 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(){
        super.init()
         var fixedSize = self.frame.width/11
    background.size = CGSizeMake(self.frame.width-fixedSize, self.frame.size.height-fixedSize)
    background.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
    self.addChild(background)
    }
}


 //In the main method i said let settings = menu()  self.addChild(settings)   nothing shows up

回答1:


The frame property of an SKNode is equal to CGRectZero, so when you try to set the size of your background node it will also end up as CGRectZero.

An easy fix to your problem would be to add custom initializer and call that with the size of the scene.

class menu:SKNode {
    let background = SKSpriteNode(imageNamed:"background") 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    init(size: CGSize) {
        super.init()
        var fixedSize = size.width/11
        background.size = CGSizeMake(size.width-fixedSize, size.height-fixedSize)
        background.position = CGPointMake(size.width/2, size.height/2)
        self.addChild(background)
    }
}


来源:https://stackoverflow.com/questions/35237669/sknode-cant-see-added-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!