【问题标题】:AS3 AI hitTestObject with itself?AS3 AI hitTestObject 本身?
【发布时间】:2012-01-05 22:25:48
【问题描述】:

我创建了一个每 1 秒启动一次的计时器。 这是每 1 秒发生一次的代码。

var Random_Value_X:Number = Math.ceil(Math.random() * 1500);
var Random_Value_Y:Number = Math.ceil(Math.random() * 2000);

var enemy:MovieClip = new AI(stage);
addChild(hero);
enemy.x = Random_Value_X;
enemy.y = Random_Value_Y;

好的。然后我得到了一个叫做 AI 的类,我已经做了它,所以 AI 跟随我的玩家。问题是,我需要做一个 hitTest 来测试一个 AI 是否击中另一个 AI?有没有办法可以给每个新的 AI 一个 ID?就像第一个被称为“AI1”和第二个 AI2”,然后我可以编写一个类似 If(AT1.hitTestObject(AT2 || AT3)) 的代码

希望您能理解我要解释的内容! :)

【问题讨论】:

    标签: actionscript-3 timer artificial-intelligence hittest


    【解决方案1】:

    你应该把它们都放在一个数组中。然后你可以循环遍历数组并对每个数组进行命中测试。根据您拥有的数量,您可能需要将它们分成几组,这样您就不必在每一帧中进行如此多的检查。

    我很确定你不能像那样只使用逻辑或在 hitTestObject 方法中。

    【讨论】:

    • 谢谢!我可能忘了说我几乎是 AS3 的新手,所以如果您可以并且想要写下一些代码,那就太好了!我没怎么用过数组。
    【解决方案2】:

    考虑到您在 root 上,并且关键字“this”指的是 root。如果您创建类“enemy”的实例,那么它的所有对象都将具有“enemy”类型。

    import flash.events.Event;
    
    // for every enemy you create, addlistener to it
    // it will force to check itself with others
    enemy.addEventListener(Event.ENTER_FRAME,checkHit);
    
    // this function will be available to all enemies
    // will inform itself that it is hiting enemy instance
    
    function checkHit(e:Event){
    // for e.g. object is moving in x direction
    // to keep it simple so you can run it in new file
    // with two object one is called enemy and other enemy1
    
    // in your case its changing position
    e.target.x += 1;
    
    
    // loop with all children, break when hit someone   
    for(var i:uint=0;i<this.numChildren;i++){
    // in current situation e.target is also a child of root
    // therefore avoid checking it
        if(e.target==this.getChildAt(i)) continue;//trace("Its me");
    
    // if hit
    // currently testing hit with all objects on stage
    // you can change it to check specific type
        if(e.target.hitTestObject(this.getChildAt(i))){
            trace("I got hit by: "+this.getChildAt(i).toString());
            break;
        }
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多