如果每个仆从都有一个目标炮塔,那么你应该在你的Minion
类中保存对炮塔的引用。不需要静态函数来获取距离(除非它用于除小兵/炮塔关系之外的其他事物)。
为了让您的炮塔了解所有小兵(以决定攻击哪个小兵),一个好的方法是将它们全部存储在一个静态可评估的向量(数组)中。
这是您的 Minion 课程的示例:
public class Minion {
public static var allMinions:Vector<Minion> = new Vector<Minion>(); //create a static array to store all your minions
public var turret:Turret;
public function Minion(targetTurret:Turret):void {
turret = targetTurret;
this.addEventListener(Event.ADDED_TO_STAGE,addedToStage,false,0,true);
this.removeEventListener(Event.REMOVED_FROM_STAGE,removedFromStage,false,0,true);
}
private function addedToStage(e:Event):void {
allMinions.push(this); //add this minion instance to the array when it's added to the display list
}
private function removedFromStage(e:Event):void {
//remove this minion instance from the array of all minions when it's removed from the display list
var index:int = allMinions.indexOf(this);
if(index >= 0){
allMinions.splice(index,1);
}
}
private function move():void { //whatever function you use to move the minion along
//get distance here, using your local turret var
getDistance(this,turret); //this could be a local function, or some static function somewhere - local is faster, especially if being called everyframe or in a loop.
}
//a function to take damage, returns true if still alive after the damage
public function takeDamage(amount:Number):Boolean {
this.health -= amount * armor; //armor could be a value between 1 (no armor) and 0 (invincible)
if(health <= 0){
//die
return false;
}
return true;
}
}
当你创建一个新的 Minion - 时,它会传入适当的炮塔new Minion(turretInstance)
,并且有一个静态可访问的数组,其中包含在任何给定时间显示列表上的所有 Minion。它还增加了一个受到伤害的功能
对于要攻击的炮塔,您需要扫描所有仆从的阵列,并确定哪些离攻击足够近,要么攻击所有(如果这是炮塔的类型),要么选择一个(通常是最近的)进行攻击。
炮塔类:
public var range:Number = 200; //how close to the turret a minion needs to be before it can attack
public var attackPower:Number = 10; //how much damage does this turret cause
public function attack():void {
//this for loop goes through all the minions and finds the closest one
var closestMinion:Minion;
var tmpDistance:Number; //
var distance:Number;
for each(var minion:Minion in Minion.allMinions){
distance = Math.sqrt( ( minion.x - this.x ) * ( minion.x - this.x ) + ( minion.y - this.y ) * ( minion.y - this.y ) ); //find the distance between the current minion in the loop and this turret
if(distance < range && isNaN(tmpDistance) || distance < tmpDistance){ //if the distance of this minion is less than the current closest, make the current closest this one
closestMinion = minion;
tmpDistance = distance;
}
}
//attack the closest one
if(closestMinion){
closestMinion.takeDamage(attackPower);
}
}