我正在尝试将对象的子实例添加到舞台,然后允许用户将此对象(在本例中为电影剪辑)拖放到舞台上。但是,我收到以下错误:
TypeError:错误 #1009:无法访问空对象引用的属性或方法。在working_copy_fla::MainTimeline/dragObject()
所以,这是我的第一个问题。然后第二个问题,我还没有找到关于如何使子对象(特别是电影剪辑)能够在舞台上正确拖放的答案。
这是我的代码:
// Allow buttons to bring objects to the stage
myButton.addEventListener(MouseEvent.CLICK, addImage);
function addImage(event:MouseEvent):void
{
var myImage:Image_mc = new Image_mc();
stage.addChild(myImage);
// Center the object
myImage.x = 300;
myImage.y = 300;
// Allow the object to be drag and dropped
myImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
myImage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}
function startDragging(event:MouseEvent):void
{
event.target.x = event.target.parent.mouseX - event.target.mouseX
event.target.y = event.target.parent.mouseY - event.target.mouseY
stage.addEventListener(MouseEvent.MOUSE_MOVE, dragObject);
}
function dragObject(event:MouseEvent):void
{
event.target.x = event.target.parent.mouseX - event.target.mouseX
event.target.y = event.target.parent.mouseY - event.target.mouseY
}
function stopDragging(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragObject);
}
编辑
我想通了,解决方案就像查看 Adobe Flash 中的示例代码(使用 CS6)一样简单。这是我现在的代码:
// Allow buttons to bring objects to the stage
myButton.addEventListener(MouseEvent.CLICK, addImage);
function addImage(event:MouseEvent):void
{
var myImage:Image_mc = new Image_mc();
stage.addChild(myImage);
// Center the object
myImage.x = 300;
myImage.y = 300;
// Allow the object to be dragged
myImage.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
}
function clickToDrag(event:MouseEvent):void
{
event.target.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
function releaseToDrop(event:MouseEvent):void
{
event.target.stopDrag();
}
这里的关键是我创建了可以接受来自任何对象的输入的通用函数(clickToDrag 和 releaseToDrop)(因此我可以将这些函数与我添加到舞台的其他图像一起使用)。此代码适用于舞台上的多个孩子(所有孩子都可以随时拖放)。
我现在遇到的唯一问题是,每当我生成子元素时(通过单击myButton按钮实例),我都会收到此错误:
ReferenceError: Error #1069: Property stopDrag not found on flash.display.SimpleButton and there is no default value.
at working_copy_fla::MainTimeline/releaseToDrop()
此错误不会阻止应用程序工作;一切仍然运行良好。但我仍然想弄清楚为什么会发生这个错误。我的猜测是,使用“stopDrag”(应该只是一个电影剪辑)的任何东西都不能使用这种方法。