嵌套函数会降低性能吗?

时间:2014-08-09 20:06:54

标签: actionscript-3 flash nested-function

我在侧面滚轮式游戏中有一个类UglyLobster,它在AS3中使用人工智能。 UglyLobster是一个很大程度上自我操作的类,它根据环境确定接下来会做什么。在构建这种人工智能时,我发现最简单的解决方案是使用嵌套函数。

但是,我不确定嵌套函数是否会影响性能并导致拖动。此UglyLobster不限于一个实例;很多人会在同一时间跑步。我已经添加了代码来展示我尝试做的事情。

public class UglyLobster extends Mob {

    //these vars determine what the UglyLobster will do next
    public var behavior = "aggro"
    private var behaviorStep:int = 1

    public function UglyLobster() {
        addEventListener(Event.ENTER_FRAME,performBehavior)
    }

    public function performBehavior(e) {
        if (behavior == "aggro") {
            aggro()
        }
        if (behavior == "tranq") {
            tranq()
        }
    }

    private function aggro() {
        //it is necessary to have multiple steps.
        //in step 1, the Lobster could bare its lobster fangs,
        //then in step 2, crawl toward a point
        //and in step 3, pinch somebody
        if (behaviorStep == 1) {
            step1()
        }
        if (behaviorStep == 2) {
            step2()
        }
        if (behaviorStep == 3) {
            step3()
        }
        function step1() {
            if (someCondition) {
                behaviorStep = 2
            } else {
                //do whatever happens in step1
            }
        }
        function step2() {
            if (someOtherCondition) {
                behaviorStep = 3
            } else {
                //do whatever happens in step2
            }
        }
        function step3() {
            if (anotherCondition) {
                behaviorStep = 1
            } else {
                behavior = "tranq"
            }
        }
    }

    private function tranq() {
        //do nothing
    }

}

嵌套函数是一种完成任务的内存有效方法吗?如果没有,您将如何为UglyLobster设置人工智能?实例真的有帮助

1 个答案:

答案 0 :(得分:0)

即使我不喜欢这种设计,并且正如Jason所说,可能存在架构设计问题,我认为不需要嵌套函数。

private function aggro() {
    //it is necessary to have multiple steps.
    //in step 1, the Lobster could bare its lobster fangs,
    //then in step 2, crawl toward a point
    //and in step 3, pinch somebody
    if (behaviorStep == 1) {
        step1()
    }
    if (behaviorStep == 2) {
        step2()
    }
    if (behaviorStep == 3) {
        step3()
    }
}

private function step1() {
    if (someCondition) {
         behaviorStep = 2
    } else {
         //do whatever happens in step1
    }
}

private function step2() {
        if (someOtherCondition) {
            behaviorStep = 3
        } else {
            //do whatever happens in step2
        }
 }

private function step3() {
        if (anotherCondition) {
            behaviorStep = 1
        } else {
            behavior = "tranq"
        }
}