Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Actionscript 3 Actionscript:父对象的大小取决于子对象';s宽度和坐标_Actionscript 3_Actionscript - Fatal编程技术网

Actionscript 3 Actionscript:父对象的大小取决于子对象';s宽度和坐标

Actionscript 3 Actionscript:父对象的大小取决于子对象';s宽度和坐标,actionscript-3,actionscript,Actionscript 3,Actionscript,我对父精灵的宽度有问题。我创建了两个精灵:父精灵和子精灵 var parent:Sprite = new Sprite(); var child:Sprite = new Sprite(); addChild(parent); parent.addChild(child); child.x = 20; child.y = 20; child.graphics.beginFill(0xFF0000); child.graphics.drawRect(0, 0, 100, 100); trace

我对父精灵的宽度有问题。我创建了两个精灵:父精灵和子精灵

var parent:Sprite = new Sprite();
var child:Sprite = new Sprite();

addChild(parent);
parent.addChild(child);

child.x = 20;
child.y = 20;
child.graphics.beginFill(0xFF0000);
child.graphics.drawRect(0, 0, 100, 100);
trace("colorBox.graphics.beginFill(0xFF0000);");
trace("colorBox.graphics.drawRect(0, 0, 100, 100);");
trace("parent", parent.width, parent.height, parent.x, parent.y);
trace("child", child.width, child.height, child.x, child.y);
如果我在精灵上添加精灵,parent.width为100,即使child.x=20。同样的高度和y

但如果我像这样更改代码:

var parent:Sprite = new Sprite();
var child:Sprite = new Sprite();

parent.graphics.drawRect(0, 0, 0, 0); // the difference

addChild(parent);
parent.addChild(child);

child.x = 20;
child.y = 20;
child.graphics.beginFill(0xFF0000);
child.graphics.drawRect(0, 0, 100, 100);
trace("colorBox.graphics.beginFill(0xFF0000);");
trace("colorBox.graphics.drawRect(0, 0, 100, 100);");
trace("parent", parent.width, parent.height, parent.x, parent.y);
trace("child", child.width, child.height, child.x, child.y);
父宽度变为等于120


为什么会这样?如果没有“parent.graphics.drawRect”hack,如何按child调整父对象的宽度?

精灵的宽度不一定是从原点(0,0)计算出来的。它是基于其中元素的边界计算的,从内容的最左侧点开始。由于子元素的最左端点是20,因此从那里计算宽度。将图形添加到(0,0)时,将从新的最左侧点(0,0)计算宽度

有两种方法可以解决此问题:

创建自己的宽度计算方法,该方法基于子对象的偏移和宽度返回宽度:

function myWidth():Number {
    return child.x + child.width;
}
执行您已经完成的操作,并将一个不可见元素添加到父元素的原点


参考资料:

谢谢你,克雷格!我们一整天都无法处理这个问题。