swift - how to add SKSpriteNode in a loop -
i want add squares in scene loop. code has problem. wrong?
var shape = skspritenode(color: uicolor.redcolor(), size: cgsize(width: 100, height: 100)) (var i=0 ; i<10 ; i++) { shape.name = "shape\(i)" shape.position = cgpointmake(20,20) self.addchild(shape) }
you have few issues here. current code trying add same skspritenode multiple times same parent (scene). impossible because 1 node can have 1 parent @ time. thing, not issue, can confuse you adding multiple nodes @ same position can looks 1 node added.
what have create copies of "shape" variable , add them accordingly scene, this:
import spritekit class gamescene: skscene { override func didmovetoview(view: skview) { var shape = skspritenode(color: uicolor.redcolor(), size: cgsize(width: 20, height: 20)) (var i=0 ; i<10 ; i++) { var sprite = shape.copy() skspritenode sprite.name = "shape\(i)" sprite.position = cgpointmake(20 + cgfloat(i*30) , cgrectgetmidy(self.frame) ) self.addchild(sprite) } } } otherwise if run code, error adding node has parent. hope helps understand what's happening.
not related this, may find useful enable debugging labels (if haven't already) in view controller see information node count, draws count, visual physics representation , more. can save future headaches. here how enable that:
(in viewdidload method or whatever method use initialize scene):
skview.showsfps = true skview.showsnodecount = true skview.showsphysics = true skview.showsdrawcount = true
Comments
Post a Comment