2012-03-15 101 views
0

我是ActionScript新手,我有一個問題。Actionscript Class Communication

我是一個班級,「敵人」。這個類有一個「碰撞」功能。我該如何與球員在這堂課中留下的生命數量交流?謝謝。

+0

儘管我真的很不喜歡大量事件驅動的遊戲,但它可能與[ActionScript類號通信]重複(http://stackoverflow.com/questions/9728927/actionscript-class-number-communication) – Marty 2012-03-15 23:06:52

回答

2

嘗試這樣:

public class Game extends MovieClip { 
    public var enemy:Enemy; //enemy can be a timeline instance 
    public var player:Player //can also be a timeline instance 
    public function Game() { 
     super(); 
     //for this to work enemy must exist on frame one of the Game MC 
     //and stay around for the rest of the MC's lifespan 
     enemy.addEventListener(EnemyEvent.COLLISION, onEnemyCollision); 
    } 
    protected function onEnemyCollision(e:EnemyEvent):void { 
     e.player.lives--; 
    } 
} 

//the enemy!!! 
public class Enemy extends Sprite { 
    //I actually don't understand why this is a function on enemy. 
    //I wouldn't have designed it this way. 
    //What is calling it? 
    public function collision(withPlayer:Player):void { 
     dispatchEvent(new EnemyEvent(EnemyEvent.COLLISION, withPlayer)); 
    } 
} 

//the player 
public class Player extends Sprite { 
    public var lives:int=10; 
} 

//the enemy event 
public class EnemyEvent extends Event { 
    public static const COLLISION:String = 'Big badda boom.';//Fifth Element reference 
    public var player:Player; 
    public function EnemyEvent(type:String, player:Player) { 
     super(type, true, true); 
     this.player = player; 
    } 
    public function clone():Event { 
     new EnemyEvent(type, player); 
    } 
} 

如果你不希望有一個幀的播放器和敵人,看看這個職位更多關於這個東西是如何工作的深度:http://www.developria.com/2010/04/combining-the-timeline-with-oo.html。或者你可以編寫代碼來手動添加它們,但這太像工作了。

+0

'+ 1'。 – Marty 2012-03-16 02:44:57

+0

在這種情況下,OP可能不需要事件。我懷疑稱爲「碰撞」的「東西」也知道玩家,但這不是問題的表達方式。 – 2012-03-16 17:16:23

相關問題