Actionscript 3 如何使用按钮从库中添加对象(使用Math.random作为位置)?

Actionscript 3 如何使用按钮从库中添加对象(使用Math.random作为位置)?,actionscript-3,Actionscript 3,我有一个小项目,我被要求创建一个按钮,它将随机地将一个对象从库放到舞台上。我知道如何使用按钮将预定义项从库中放置到舞台上,以及如何使用for循环将对象的新实例推入其中,但我不知道如何创建、设置随机坐标,以及如何将子对象放置到舞台上 // subtract the size of the object to prevent it from // moving outside the bounds of the stage inst.x = Math.random() * stage.stageWi

我有一个小项目,我被要求创建一个按钮,它将随机地将一个对象从库放到舞台上。我知道如何使用按钮将预定义项从库中放置到舞台上,以及如何使用for循环将对象的新实例推入其中,但我不知道如何创建、设置随机坐标,以及如何将子对象放置到舞台上

// subtract the size of the object to prevent it from
// moving outside the bounds of the stage
inst.x = Math.random() * stage.stageWidth - inst.width;
inst.y = Math.random() * stage.stageHeight - inst.height;

我会发布我拥有的代码,但没有一个代码能工作一点点。我试着使用getDefinitionByName并将其放入数组,然后将其放到舞台上,但不使用nada。我似乎无法解决这个问题。有什么想法吗?

如果你知道如何将物体添加到你的舞台上,那么就没有更多的科学知识了

//Your button
button.addEventListener(MouseEvent.CLICK, addItem);

//function to generate random coord.
function addItem(e:MouseEvent):void {
   var c:DisplayObject = new YourItemInLibrary();
   c.x = Math.random() * stage.stageWidth;
   c.y = Math.random() * stage.stageHeight;
   addChild(c);
}

我从未在AS3(仅AS2)中与图书馆合作过,因此在这方面我帮不了你。其余的都相当简单

因此,您可以创建库项的实例。同样,我也不知道怎么做,所以我将用一个简单的
Sprite
创建一个示例

var inst:Sprite = new Sprite();
要将其添加到stage,可以对主对象调用
addChild
。除非你有特定的理由,否则你永远不要在
阶段调用它。在这种情况下,我将假设主对象将只是主
MovieClip
对象,可以使用
this
关键字来引用它

this.addChild( inst );
要随机放置它,我们将使用
Math.random()
。该方法生成一个介于0和1之间的数字。为了将其随机放置在舞台上,我们将乘以舞台的大小

// subtract the size of the object to prevent it from
// moving outside the bounds of the stage
inst.x = Math.random() * stage.stageWidth - inst.width;
inst.y = Math.random() * stage.stageHeight - inst.height;

这样将创建一个对象,将其添加到舞台,并将其移动到舞台上的随机位置,而不会超出舞台的边界。你只需要用你的库对象替换我的通用
Sprite
实例化,并将其全部放入一个循环中(我可以假设你知道怎么做,或者至少谷歌可以弄清楚)

我有一些非常类似的东西,但我需要能够按按钮放置尽可能多的对象。如果你按下按钮10次,理想情况下会有10个项目在屏幕上随机分布。按钮正好可以做到这一点。每次按下对象时添加该对象。听众永远不会被删除。有时我觉得我不应该和AS3一起工作。。。这工作做得很好!谢谢D