1

我想在 ActionScript-3 中为 Sprite 类添加更多功能。基本上添加变量和方法。我有这个我不太喜欢的工作解决方案,因为我需要通过其完整路径引用 Sprite:

package myPackage
{
    import flash.display.Sprite;
    import myPackage.Sprite;

    public class Sprite extends flash.display.Sprite
    {
        public function Sprite()
        {
            super();
            graphics.lineStyle(3, 0xff00ff);
            graphics.drawRect(0, 0, 64, 64);
            doStuff();
        }

        public function doStuff(): void
        {
            trace("hello world");
            if (Math.random() < 0.9)
                addChild(new myPackage.Sprite());
        }
    }
}

尽管没有这两个导入,Java 编译器可以很好地处理,但缺少导入给了我这些错误:

  • 错误:对 Sprite 的引用不明确。
  • 错误:未找到基类 Sprite 的定义。

是否有另一种方法可以将变量、属性和方法添加到 Sprite 并在之后使用新的 Sprite 作为类?如果进行原型设计,是否有一个简单易行的示例?

4

2 回答 2

0

I recommend picking another class name for your subclass. Even if you find a way to replace Adobe's Sprite with your own, this is a bad idea. Also, unless you have the source code for an existing subclass of Sprite, I recommend against trying to change it directly (eg. recompiling as a child of your Sprite class rather than Adobe's Sprite class).

Sprite is a very commonly used class, and you will probably want another developer to be able to follow your code some day. If you use 'EnhancedSprite' or similar, it will be obvious that there is more/different functionality available.

It is obvious why you need to use the full class path when you try to use the same class name. This will always be the case within your Sprite/EnhancedSprite file. If you really must use the name 'Sprite', You need to find a way to have your actionscript compiler import all of the Adobe classes except Sprite, plus your own sprite class.

If you want all sprite subclasses to extend from your improved class, you basically need to recompile them all (MovieClip being the big one I personally don't mess with under the hood). This is also a bad idea, because an existing subclass could have a method matching the name of your own method and would cause further problems. For example, if you have a method stop(), how will MovieClip be compiled? Before using 'doStuff' as a method name, you would have to check that no existing subclass of Sprite already has that as a method or variable name, whether public or private.

于 2013-04-13T22:38:52.180 回答
0

首先,您的 myPackage.Sprite 类中不需要这一行:

import myPackage.Sprite;

可能发生的情况是,在您创建此 Sprite 实例的任何类中,您都导入了两个 Sprite 类,但您没有在该类中明确指定包。

例如,如果在您的 Main 类中,您有以下导入:

 import flash.display.Sprite;
 import myPackage.Sprite;

无论您在何处使用该类名,都需要明确。如果你不是,你很可能会得到你一直得到的错误。

例如,如果您同时导入了以下内容,则会出现该错误:

var mySprite:Sprite = new Sprite;

您应该在适当的地方执行以下操作:

var mySprite:myPackage.Sprite = new myPackage.Sprite;
var regSprite:flash.display.Sprite = new flash.display.Sprite;

另外,您是用 CS6 还是 Flash Builder 或 Flash Develop 编译?

于 2013-04-14T21:28:50.573 回答