我正在建立一个系统来管理游戏中的过场动画。但是,我遇到了一个棘手的问题,很难向Google描述。我需要访问Flash告诉我的函数“未定义”。
这就是我所拥有的;Cutscene
是一个基类,其中包含所有过场动画的基本功能Cutscene1
扩展Cutscene
,并包含有关单个过场动画的信息。这些信息包括函数和变量。以后会出现Cutscene2,
Cutscene3
,所有这些都将扩展为Cutscene
CutsceneHandler
进行Cutscene
,确定Cutscene
的下一步,并告诉Cutscene
执行该步骤定义的功能。CutsceneHandler
仅接受Cutscene
因此,我们给此处理程序一个新实例化的Cutscene1
。 Handler说:“嘿,这是一个Cutscene
,一切都很棒。”但是现在,处理程序告诉Cutscene
执行仅在其子类中定义的功能。 Handler说:“哇,Cutscene
类没有这样的功能!”并引发错误。调用可能未定义的函数。
我们如何解决这个问题?我们如何调用函数有问题吗?我在下面包括了一些简化的代码。
public class CutsceneHandler extends Sprite {
var activeCutscene:Cutscene
public function CutsceneHandler() {
//empty constructor
}
public function beginCutscene(cutscene:Cutscene) {
activeCutscene = cutscene
executeStep(activeCutscene.steps[0])
}
public function executeStep(step:Object) {
if (step.action) {
activeCutscene.action()
}
}
}
__
public class Cutscene1 extends Cutscene {
public var steps = [
{action:someFunction,someImportantDetail:true},
{action:someOtherFunction,someImportantDetail:false}
]
public function Cutscene1() {
//empty constructor
}
public function someFunction() {
trace ("hello!")
}
public function someOtherFunction() {
trace ("goodbye!")
}
}
最佳答案
这听起来像command pattern的工作!
用简单的话说,想法是将每个步骤的细节封装在单独的类实例中,这些实例都使用单个execute
方法实现接口。您的处理程序类可以通过该接口调用步骤,而无需了解步骤所属的Cutscene
的特定子类。
如下所示的内容应该可以使您朝正确的方向前进。
ICommand接口:
public interface ICommand {
function execute():void
}
具体命令:
public class HelloCommand implements ICommand {
public function execute():void {
trace("hello");
}
}
public class GoodbyCommand implements ICommand {
public function execute():void {
trace("goodbye");
}
}
过场动画的子类
public class Cutscene1 extends Cutscene {
// Declare steps variable in the base class since
// all subclasses will use it
public function Cutscene1() {
// Define the steps specific to this subclass
steps = [
new HelloCommand(),
new GoodbyeCommand()
];
}
}
处理程序类
// Only extend Sprite if the class needs to be displayed
public class CutsceneHandler {
var activeCutscene:Cutscene
public function CutsceneHandler() {
//empty constructor
}
public function beginCutscene(cutscene:Cutscene) {
activeCutscene = cutscene;
// Cast the step as ICommand and execute it
(activeCutscene.steps[0] as ICommand).execute();
}
}
关于actionscript-3 - 引用由Actionscript 3中的子类定义的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25750866/