报错的的代码:
this.parent.addChild(this.child);
非常简单的添加子节点的代码(也可以理解为添加父级)
运行的时候莫名奇妙的就爆出:
ERROR: Uncaught Error: child already added. It can't be added again, location: src/jsb_polyfill.js:0:0
Simulator: STACK:
Simulator: [0]cc.assert@src/jsb_polyfill.js:56
Simulator: [1]anonymous@src/jsb_polyfill.js:81
Simulator: [2]anonymous@src/jsb_polyfill.js:98
Simulator: [3]cc.assertID@src/jsb_polyfill.js:86
Simulator: [4]addChild@src/jsb_polyfill.js:3096
解决方法:
this.child.parent = this.parent;
使用该方案解决有一个弊端: 子节点的位置信息没有更新(子节点的位置还是设置父级之前的位置)
解决方法:就是在设置父级的时候计算出child节点的世界坐标,设置完父级之后,再把该世界坐标转换成父级的局部坐标
终极添加子节点代码:
public addChild(parent:cc.Node,child:cc.Node):void
{
let worldPos = child.position;
if (child.parent != null)
{
worldPos = child.parent.convertToWorldSpaceAR(child.position);
}
child.parent = parent;
child.position = parent.convertToNodeSpaceAR(worldPos);
}
喜欢的朋友加个关注吧
在Cocoscreator中遇到ERROR: Uncaught Error: child已经添加,无法再次添加的问题。这个问题出现在尝试添加已经存在于场景中的子节点时。解决方法包括在设置父级时计算并更新子节点的世界坐标,确保其位置正确。提供了一段终极添加子节点的代码,以避免此错误并保持子节点位置更新。
4004

被折叠的 条评论
为什么被折叠?



