2012-03-15 62 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

相关问题