2011-05-08 2 views
0

나는 현재 게임을 만들려고 노력하고 있어요,하지만 문제는 지금은 내 주 만에 dispatchEvent 때이다 클래스가 엔진을 선택합니다. 내 무기도 가져다 주자. 내 주 수업은 Engine.as (무대 수업에 배정 됨)이고 내 무기는 우주선입니다. Score.as라는 수업에서 이벤트를 파견합니다. 는, dispatchEvent은 내 메인 클래스 (Engine.as)이 아닌 선박 클래스 (Weapons.as)에 의해 포착됩니다

가장 큰 문제

내 Weapons.as는 "gameO"이나 "gameOver"이벤트는 score.as 파견을 선택하지 않습니다. 또 다른 것은 if (s_hp == 100) (시작하는 부분)을 설정하면 Weapons.as는 전달되는 이벤트를 픽업 할 수 있지만 그 후에 만 ​​...

될 수 있습니다. 더 구체적으로 말하자면, 스코어에서 이벤트를 버블 링해야합니다. 무기를 통해 내 메인 클래스 엔진으로. Weapons.as의 eventListener가 이벤트를 가져와 우주선을 제거하고 촬영할 수 없게 만든 다음 이벤트를 Engine.as 클래스로 전달하여 스테이지에서 거의 모든 것을 제거합니다.

도움말보기 나는 얻다! :)

편집 : 전체 클래스

Score.as :

package Etys 
{ 

    import flash.display.MovieClip; 
    import flash.display.Stage; 
    import flash.text.TextField; 
    import flash.events.Event; 
    import flash.utils.Timer; 
    import flash.geom.ColorTransform; 

    public class Score extends MovieClip 
    { 

     private var stageRef:Stage; 
     public var s_score:Number = 0; 
     public var s_hits:Number; 
     public var s_kills:Number = 0; 


     public function Score(stageRef:Stage) 
     { 

      this.stageRef = stageRef; 
      s_hits = 100; 
      healthBar.width = 100; 
      kills.text = "Kills: \n0"; 
      hits.text = "HP: \n100"; 
      score.text = "Score: \n0"; 
      kills.selectable = false; 
      hits.selectable = false; 
      score.selectable = false; 

      x = 10; 
      y = stageRef.stageHeight - height; 
      addEventListener(Event.ENTER_FRAME, loop, false, 0, true); 

     } 

     public function updateKills(value:Number) : void 
     { 
      s_kills += value; 
      kills.text = String("Kills: \n"+s_kills); 
      trace(s_hits+"I Kills"); 
     } 

     public function updateHits(value:Number) : void 
     { 
      if(s_hits != 1 || s_hits != 0) 
      { 
       s_hits -= value; 
       healthBar.width -= value; 
       hits.text = String("HP: \n"+s_hits); 
      }else{ 
       healthBar.width = 0; 
       s_hits = 0; 
       hits.text = String("HP: \n"+s_hits); 
      } 

      if(s_hits == 66 ||s_hits == 67) 
      { 
       var colorYellow:ColorTransform = healthBar.transform.colorTransform; 
       colorYellow.color = 0xFFFF00; 
       healthBar.transform.colorTransform = colorYellow; 
      }else if(s_hits == 33 || s_hits == 34) 
      { 
       var colorRed:ColorTransform = healthBar.transform.colorTransform; 
       colorRed.color = 0xFF0000; 
       healthBar.transform.colorTransform = colorRed; 
      } 


      s_score -= value; 
      score.text = String("Score: \n"+s_score); 
      trace(s_hits+"I Hits"); 

     } 


     public function updateScore(value:Number) : void 
     { 
      s_score += value; 
      score.text = String("Score: \n"+s_score); 
      trace(s_hits+"I Score"); 

     } 

     public function loop(e:Event) 
     { 
      if(s_hits == 99 || s_hits == 98) 
      { 
       this.dispatchEvent(new Event('gameOver', true)); 
       this.dispatchEvent(new Event('gameO', true)); 
       removeEventListener(Event.ENTER_FRAME, loop); 
      } 
     } 



    } 

} 

Weapons.as :

package Etys 
{ 

    import flash.display.MovieClip; 
    import flash.display.Stage; 
    import com.senocular.utils.KeyObject; 
    import flash.ui.Keyboard; 
    import flash.events.Event; 
    import flash.utils.Timer; 
    import flash.events.TimerEvent; 

    public class Weapons extends MovieClip 
    { 

     private var stageRef:Stage; 
     private var key:KeyObject; 
     private var speed:Number = 2; 
     private var vx:Number = 0; 
     private var vy:Number = 0; 
     private var friction:Number = 0.93; 
     private var maxspeed:Number = 8; 
     private var target:Stinger; 
     public var score:Score; 


     private var fireTimer:Timer; 
     private var canFire:Boolean = true; 
     private var stopIt:Boolean = false; 

     public function Weapons(stageRef:Stage) 
     { 

      this.stageRef = stageRef; 


      score = new Score(stageRef); 

      addChild(score); 

      score.addEventListener('gameO', lostGame, false, 0, false); 
      addChild(score); 
      key = new KeyObject(stageRef); 


      fireTimer = new Timer(200, 1); 
      fireTimer.addEventListener(TimerEvent.TIMER, fireTimerHandler, false, 0, true); 

      addEventListener(Event.ENTER_FRAME, loop, false, 0, true); 


     } 

     public function loop(e:Event) : void 
     { 

      if (key.isDown(Keyboard.A)) 
      { 
       vx -= speed; 
      }else if (key.isDown(Keyboard.D)) 
      { 
       vx += speed; 
      }else{ 
       vx *= friction; 
      } 
      if (key.isDown(Keyboard.W)) 
      { 
       vy -= speed; 
      }else if (key.isDown(Keyboard.S)) 
      { 
       vy += speed; 
      }else{ 
       vy *= friction; 
      } 
      if (key.isDown(Keyboard.SPACE)) 
      { 
       fireBullet(); 
      } 


      //update position 
      x += vx; 
      y += vy; 

      //speed adjustment 
      if (vx > maxspeed) 
      { 
       vx = maxspeed; 
      }else if (vx < -maxspeed) 
      { 
       vx = -maxspeed; 
      } 
      if (vy > maxspeed) 
      { 
       vy = maxspeed; 
      }else if (vy < -maxspeed) 
      { 
       vy = -maxspeed; 
      } 
      //ship appearance 
      rotation = vx; 
      scaleX = (maxspeed - Math.abs(vx))/(maxspeed*4) + 0.75; 

      //stay inside screen 
      if (x > 537) 
      { 
       x = 537; 
       vx = -vx; 
      } 
      else if (x < 13) 
      { 
       x = 13; 
       vx = -vx; 
      } 

      if (y > 378) 
      { 
       y = 378; 
       vy = -vy; 
      } 
      else if (y < 216) 
      { 
       y = 216; 
       vy = -vy; 
      } 


     } 


     public function lostGame(e:Event) 
     { 
      trace("bash"); 
      fireTimer.stop(); 
      fireTimer.reset(); 
      canFire = false; 
      fireTimer.removeEventListener(TimerEvent.TIMER, fireTimerHandler); 
      removeEventListener(Event.ENTER_FRAME, loop); 

     } 

     private function fireBullet() : void 
     { 
      //if canFire is true, fire a bullet 
      //set canFire to false and start our timer 
      //else do nothing. 
      if (canFire) 
      { 
       stageRef.addChild(new LaserBlue(stageRef, x + vx +15, y - 10)); 
       stageRef.addChild(new LaserBlue2(stageRef, x + vx -15, y - 10)); 
       canFire = false; 
       fireTimer.start(); 
      } 

     } 

     //HANDLERS 

     private function fireTimerHandler(e:TimerEvent) : void 
     { 
      //timer ran, we can fire again. 
      canFire = true; 
     } 

     public function hitShip() : void 
     { 
      dispatchEvent(new Event("hitShipe")); 
     } 
     public function takeHit() : void 
     { 
      dispatchEvent(new Event("hit")); 
     } 

    } 

} 

엔진 :

package Etys 
{ 
    import flash.display.MovieClip; 
    import flash.display.Stage; 
    import flash.events.MouseEvent; 
    import flash.events.Event; 
    import flash.events.TimerEvent; 
    import flash.media.SoundChannel; 
    import flash.utils.Timer; 
    import flash.display.*; 


    public class Engine extends MovieClip 
    { 


     private var numStars:int = 80; 
     private var numAsteroids:int = 4; 

     public static var enemyList:Array = new Array(); 
     public static var enemyListFatso:Array = new Array(); 

     private var ourShip:Weapons; 

     private var quality:qualityButton; 
     private var score:Score; 

     public function Engine() : void 
     { 



       ourShip = new Weapons(stage); 
       stage.addChild(ourShip); 
       ourShip.x = stage.stageWidth/2; 
       ourShip.y = stage.stageHeight/2; 
       ourShip.addEventListener("hit", shipHit, false, 0, true); 
       ourShip.addEventListener("hitShip", Hit, false, 0, true); 


       for (var i:int = 0; i < numStars; i++) 
       { 
        stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip)); 
       } 

       for (var a:int = 0; a < numAsteroids; a++) 
       { 
        stage.addChildAt(new Asteroids(stage), stage.getChildIndex(ourShip)); 
       } 
       quality = new qualityButton(stage);    
       stage.addChild(quality); 

       score = new Score(stage);//create our HUD 
       stage.addChild(score); 
       score.addEventListener("gameOver", lostGame, false, 0, true); 

       //running a loop now.... so we can keep creating enemies randomly. 
       addEventListener(Event.ENTER_FRAME, loop, false, 0, true); 

     } 




     private function lowQ(e:MouseEvent) 
     { 
      stage.quality = StageQuality.LOW; 
      trace("Low"); 
     } 

     private function highQ(e:MouseEvent) 
     { 
      stage.quality = StageQuality.BEST; 
      trace("High"); 
     } 


     //our loop function 
     private function loop(e:Event):void 
     { 

      if (Math.floor(Math.random() * 90) == 4) 
      { 
       var enemyFatso:Fatso = new Fatso(stage,ourShip); 

       enemyFatso.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemyFatso, false, 0, true); 
       enemyFatso.addEventListener("killed", enemyFatsoKilled, false, 0, true); 
       enemyFatso.addEventListener("enemyC", enemyCrash, false, 0, true); 
       enemyListFatso.push(enemyFatso); 
       stage.addChild(enemyFatso); 


      } 
      //run if condition is met. 
      if (Math.floor(Math.random() * 90) == 5 || Math.floor(Math.random() * 90) == 6) 
      { 
       //create our enemy 
       var enemy:Stinger = new Stinger(stage,ourShip); 

       enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true); 
       enemy.addEventListener("killed", enemyKilled, false, 0, true); 
       enemy.addEventListener("enemyC", enemyCrash, false, 0, true); 
       enemyList.push(enemy); 
       stage.addChild(enemy); 
      } 

     } 
     private function enemyFatsoKilled(e:Event) 
     { 
      score.updateKills(1); 
      score.updateScore(e.currentTarget.points); 
     } 

     private function enemyKilled(e:Event) 
     { 
      score.updateKills(1); 
      score.updateScore(e.currentTarget.points); 

     } 

     private function enemyCrash(e:Event) 
     { 
      score.updateHits(2); 
     } 

     private function removeEnemyFatso(e:Event) 
     { 
      enemyListFatso.splice(enemyListFatso.indexOf(e.currentTarget), 1); 
     } 

     private function lostGame(e:Event) 
     { 
      dispatchEvent(new Event("removeShips", true)); 
      stage.removeChild(ourShip); 
      ourShip.removeEventListener("hit", shipHit); 
      ourShip.removeEventListener("hitShip", Hit); 
      removeEventListener(Event.ENTER_FRAME, loop); 
     } 

     private function removeEnemy(e:Event) 
     { 
      enemyList.splice(enemyList.indexOf(e.currentTarget), 1); 
     } 

     private function Hit(e:Event) 
     { 
      trace("lol"); 
     } 
     private function shipHit(e:Event) 
     { 
      score.updateHits(1); 
     } 


    } 

} 
+0

클래스의 메서드뿐만 아니라 전체 클래스를 게시 할 수 있습니까? – Taurayi

+0

게시물을 편집했습니다. 이제 모든 3 개의 클래스 전체를 추가했습니다. – Kasper

답변

0

복음 전도, ActionScript 3의 대부분은 매우 간단합니다. 객체는 이벤트를 전달하고 처리하는 리스너, 여기에 두 당사자가 상호 작용하는 방법을 보여주는 효과가 매우 간단한 예제 :

// By extending the EventDispatcher class, we can now dispatch events! Note that 
// Sprite and MovieClip both extend EventDispatcher through inheritance. 
public class Dispatcher extends EventDispatcher { 
    public function Dispatcher() { 
     // Create a simple interval which will call the "dispatchTickleEvent" 
     // method every 1.5 seconds. 
     setInterval(dispatchTickleEvent, 1500); 
    } 

    private function dispatchTickleEvent() { 
     // Broadcast an Event of type TICKLE which other classes and listen 
     // out for. 
     dispatchEvent(new Event("TICKLE")); 
    } 
} 

리스너 클래스

이벤트 디스패처 클래스

// Note that event listeners don't have to extend anything in order to listen 
// out for Events. 
public class Listener { 
    public function Listener() { 
     // Create a new instance of the Dispatcher Class. 
     var dispatcher : Dispatcher = new Dispatcher(); 

     // Here's where we add an EventListener to the Dispatcher instance. 
     // This simply means that each time the dispatcher instances emits 
     // an Event of type "TICKLE", the "onDispatcherTickled" function will 
     // be called. 
     dispatcher.addEventListener("TICKLE", onDispatcherTickled); 
    } 

    // This is the event handler method which will be called whenever our dispatcher 
    // instance broadcasts an Event of type "TICKLE". 
    private function onDispatcherTicked(event : Event) : void { 
     trace("The dispatcher was Tickled!"); 
    } 
} 

이것은 클래스가 서로 통신 할 수 있도록 느슨하게 결합 된 방식을 제공하기 때문에 매우 강력한 시스템입니다. 느슨하게 결합하면 리스너 클래스가 이벤트가 브로드 캐스트 된 원인을 알 수 없습니다 (위의 경우 간격으로 인해 자동으로 발생 함). Listener 클래스를 변경하지 않고도 동작을 수정할 수 있습니다. 예를 들어 사용자가 마우스를 클릭 할 때 Tickle 이벤트 만 전달되도록 만들 수 있습니다.

지금까지는 너무 단순하지만 이벤트에는 표시 목록의 DisplayObject가 버블 링 또는 이벤트 전파라고하는 이벤트를 전달하기 시작할 때 다소 흥미로운 특징이 있습니다.

기본 개념은 활성 표시 목록에 추가 된 DisplayObject (예 : 스프라이트)가 이벤트를 전달하면 해당 이벤트가 '상위'DisplayObjects를 통과하여 (버블) 최종적으로 스테이지에 도달합니다. 실제 Bubbling 이벤트의 좋은 예가 shown on Ruben Swieringa's blog입니다. 기사의 맨 아래로 스크롤하면 실제 영화에서 이벤트 버블 링을 보여주는 Flash Movie가 표시됩니다.

여기에 행동에 버블 링 이벤트의 매우 간단한 코드 예제 :

이벤트 디스패처 클래스, 이번에는 이벤트를 전달하는 것입니다 거품

// Note that we have to extend Sprite in order to be added to the Display List, 
// but as mentioned before, Sprite itself extends EventDispatcher further down 
// its inheritance tree. 
public class Dispatcher extends Sprite { 
    public function Dispatcher() { 
     // The interval will call dispatchTickleEvent every 1.5 seconds. 
     setInterval(dispatchTickleEvent, 1500); 
    } 

    private function dispatchTickleEvent() { 
     // Dispatch the Tickle Event, but this time notice how we pass true as 
     // the second argument when constructing the new Event() instance, this 
     // tells the Event that it should Bubble up the Display List. All of 
     // the "internal" Flash Event which are dispatched automatically, such as 
     // MouseEvent.CLICK, Event.ENTER_FRAME, etc are all set to bubble by default. 
     dispatchEvent(new Event("TICKLE", true)); 
    } 
} 

리스너 클래스, 또한 세트 디스플레이 목록 올리기

public class Listener { 
    public function Listener(stage : Stage) { 
     // Create the Dispatcher instance. 
     const dispatcher : Dispatcher = new Dispatcher(); 

     // Add the Dispatcher Instance to the Display List by adding it as a 
     // child of the Stage. 
     stage.addChild(dispatcher); 

     // Now we add the EventListeners, but instead of listening directly to 
     // the Dispatcher instance, like we did last time, we will instead listen 
     // for the Tickle event on the Stage. 
     stage.addEventListener("TICKLE", onTickleEvent); 
    } 

    private function onTickleEvent(event : Event) : void { 
     trace("Someone was tickled! :)"); 
    } 
} 

모든 클래스 인스턴스는 표시 목록에 추가 할 표시 객체이므로, 전달 된 이벤트를 표시 목록 위로 버블 링 한 다음 스테이지에 이벤트 수신기를 추가하는 것처럼 간단해야합니다.

희망 하시겠습니까?

+0

좋은, 길고 상세한 답변을 주셔서 감사합니다. 전체 dispatchEvent에 대해 더 많은 이해를 얻고 선택했습니다. 그러나 문제는 이러한 것들을 가장 많이 시도했습니다. 내 Weapons.as는 내 Score.as에 dispatchEvent를 알리는 것 같지 않습니다. 심지어 '내 Engine.as에서 가져옵니다. Engine.as 클래스가 무대 클래스이기 때문에 이것입니까? – Kasper

+0

"gameO"가 내 무기를 통해 버블 링되어야합니다. 다음으로 내 Engine.as에 추가로갑니다. 누군가가 더 설명 할 수 있다면 좋을 것입니다! :) – Kasper