A Flash Developer Resource Site

Results 1 to 15 of 15

Thread: ID to objects

  1. #1
    Senior Member
    Join Date
    Mar 2010
    Posts
    107

    ID to objects

    Hello there,

    I'm trying to create a little drag and drop game with some objects (bombs). The bombs are to walk in my screen on what number of ID is generated randomly. It then chooses a pink bomb or a blackbomb. Both bombs can be dragged(they must be dragged intro the right house), but while playing the game, more bombs of the same kind will appear , slightly more and faster.

    Now the point which is my problem is that all the bombs of the same kind stop moving when I try to drag one of the bombs, which isn 't my intention.

    I want the bombs to be dragged while the other bombs just keep appearing and I want the one draggable which the user wants to drag. So i want to give each bomb some sort of ID when dragging it.

    Can anyone see what I'm missing?

    Main class:
    Actionscript Code:
    package
    {
        import flash.display.Sprite;
        import flash.events.Event;
       
        /**
         * ...
         *
         */

        public class Main extends Sprite
        {
           
            public function Main():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
            }
           
            private function init(e:Event = null):void
            {
                removeEventListener(Event.ADDED_TO_STAGE, init);
                // entry point
                createBomb();
            }
           
            private function createBomb():void
            {
                var bomb:Bomb = new Bomb();
                addChild(bomb);
            }
           
        }
       
    }

    Bomb class:
    Actionscript Code:
    package
    {
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.events.MouseEvent;
        import flash.events.TimerEvent;
        import flash.utils.Timer;
       
        /**
         * ...
         *
         */

        public class Bomb extends Sprite
        {
            //_rndBomb is for choosing a number between 0 and 1. Pink or black bomb. Chooses randomly.
            private var _rndBomb:int;
            private var _timerEasy:Timer;
            private var _easyDelay:int = 2000;
           
            private var _blackBombsHolder:Array = [];
            private var _pinkBombsHolder:Array = [];

       
            private var _randomMovement:int;
            private var pinkBomb:PinkBomb;
       
           
           
       
           
            public function Bomb():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
            }
           
            private function init(e:Event = null):void
            {
               
                removeEventListener(Event.ADDED_TO_STAGE, init);
                _timerEasy = new Timer(_easyDelay, 0);
           
                _timerEasy.addEventListener(TimerEvent.TIMER, makeBlackBombsWithTimer);
                _timerEasy.start();
               
               
                addEventListener(Event.ENTER_FRAME, moveBombs);
           
            }
           
               
            //create pink bomb class
            private function createPinkBomb():void
            {
                pinkBomb = new PinkBomb();
                addChild(pinkBomb);
                pinkBomb.x = 275;
                _pinkBombsHolder.push(pinkBomb);
               
                pinkBomb.buttonMode = true;
               
            }
           
            private function dragPinkBomb(e:MouseEvent):void
            {
               
                e.currentTarget.velY = 0;
                //pinkBomb.velX = mouseX;
                e.currentTarget.startDrag();
               
                trace(e.currentTarget.id);
               
       
               
            }
           
            private function stopDragPinkBomb(e:MouseEvent):void
            {
                e.currentTarget.stopDrag();
                e.currentTarget.velY = 2;
            }
           
       
           
            private function createBlackBomb():void
            {
                var blackBomb:BlackBomb = new BlackBomb();
                addChild(blackBomb);
                blackBomb.x = 275;
                _blackBombsHolder.push(blackBomb);
           
       
            }
               
           
            //create black bomb class
           
           
            private function makeBlackBombsWithTimer(e:TimerEvent):void
            {
                _rndBomb = Math.ceil(Math.random() * 2);
                makeRandomBomb(_rndBomb);
           
           
            }
           
            private function moveBombs(e:Event):void
            {
                for (var i:int = 0; i < _blackBombsHolder.length; i++)
                {
                       
                        _blackBombsHolder[i].y += 2;
                       

                }
               
                for (var j:int = 0; j < _pinkBombsHolder.length; j++)
                {
                       
                        _pinkBombsHolder[j].y += pinkBomb.velY;
                        pinkBomb.id = j;
                   
                       

                }
                   
               
               
           
            }
           
           
       
           
            public function makeRandomBomb(id:int):void
            {
           
                if ( id == 1)
                {
               
                    createBlackBomb();
                    trace("black");
                   
                   
                }
               
                if ( id == 2)
                {
               
                    createPinkBomb();
                    pinkBomb.addEventListener(MouseEvent.MOUSE_DOWN, dragPinkBomb);
                    pinkBomb.addEventListener(MouseEvent.MOUSE_UP, stopDragPinkBomb);
                    trace("pink");
                }
                   
                   
            }
           
           

        }
       
    }


    PinkBomb Class:
    Actionscript Code:
    package
    {
        import flash.display.Sprite;
        import flash.events.Event;
       
        /**
         * ...
         *
         */

        public class BlackBomb extends Sprite
        {
            private var _id:int;
       
            private var _xPos:int = Math.floor(Math.random() * 100) + 50;
           
            public function BlackBomb():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
               
               
            }
           
            private function init(e:Event = null):void
            {
                removeEventListener(Event.ADDED_TO_STAGE, init);
                createBlackBomb();
            }
           
            private function createBlackBomb():void
            {
                var black:Sprite = new Sprite();
                addChild(black);
               
                black.graphics.beginFill(0x000000, 1);
                black.graphics.drawCircle(0, 0, 20);
                black.graphics.endFill();
               
                black.x = _xPos;
       
            }
           
            public function get id():int
            {
                return _id;
            }
           
            public function set id(value:int):void
            {
                _id = value;
            }
           
       
           
        }
       
    }


    PinkBomb Class:
    Actionscript Code:
    package
    {
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.events.MouseEvent;
       
        /**
         * ...
         *
         */

        public class PinkBomb extends Sprite
        {
            private var _id:int;
            private var _xPos:int = Math.floor(Math.random() * 100) + 50;
            private var _velY:int = 2;
            private var _velX:int = 0;
       

           
            public function PinkBomb():void
            {
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
           
               
            }
           
            private function init(e:Event = null):void
            {
                removeEventListener(Event.ADDED_TO_STAGE, init);
                createPinkBomb();
               
               
            }
           
           
           
            private function createPinkBomb():void
            {
                var pink:Sprite = new Sprite();
                addChild(pink);
               
                pink.graphics.beginFill(0xFF0000, 1);
                pink.graphics.drawCircle(0, 0, 20);
                pink.graphics.endFill();
               
                pink.x = _xPos
           
               
                trace(_xPos);
            }
           
            public function get id():int
            {
                return _id;
            }
           
            public function set id(value:int):void
            {
                _id = value;
            }
           
            public function get velY():int
            {
                return _velY;
            }
           
            public function set velY(value:int):void
            {
                _velY = value;
            }
           
            public function get velX():int
            {
                return _velX;
            }
           
            public function set velX(value:int):void
            {
                _velX = value;
            }
           
       
           
        }
       
    }

  2. #2
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    Also when I hold my mouse on one of those objects and leave the mouse, the object wont leave my mouse.

  3. #3
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    This code is very confused. You say you can drag both pink bombs and black bombs, but the code shows that only pink bombs get the drag handlers, which are even named dragPinkBomb and stopDragPinkBomb. But apparently names mean nothing, since makeBlackBombsWithTimer can actually make either a pink or black bomb, and you labeled both bomb classes as PinkBomb.

    You should not have a Bomb class. Or rather, you should move the Bomb management stuff to Main, or rename Bomb to BombFactory or something. There's no need for BombFactory to be a DisplayObject itself other than putting children on it. I'd just move all that to Main, which is currently doing nothing other than putting a Bomb(Factory) on itself.

    All of your pink bombs stop moving when you drag one because your moveBombs function uses pinkBomb.velY for every pink bomb's velocity, even though pinkBomb is the last added pink bomb. You should not have a pinkBomb variable. moveBombs should move the pink bombs exactly like it does the black bombs. Which brings me to the next point: You actually should have a Bomb class, but it should describe a bomb, not a collection of bombs. And PinkBomb should be a subclass of Bomb, or just a special case.
    The only time you ever iterate through your bombs is in moveBombs, and you should be handling pink and black bombs the same there. So there's really no reason to have separate black and pink bombs arrays. You should also not have _rndBomb. Just generate the random number at the appropriate time.

    Main:
    Code:
    {
        import flash.display.Sprite;
        import flash.events.Event;
        
        /**
         * ...
         * 
         */
        public class Main extends Sprite {
            private var _timerEasy:Timer;
            private var _easyDelay:int = 2000;
            private var bombs:Array = [];
            
            public function Main():void{
                if (stage) init();
                else addEventListener(Event.ADDED_TO_STAGE, init);
            }
            
            private function init(e:Event = null):void {
                removeEventListener(Event.ADDED_TO_STAGE, init);
                // entry point
                _timerEasy = new Timer(_easyDelay);
                _timerEasy.addEventListener(TimerEvent.TIMER, makeBomb);
                _timerEasy.start();
                addEventListener(Event.ENTER_FRAME, moveBombs);
            }
    
            private function moveBombs(e:Event):void {
                for (var i:int = 0; i < bombs.length; i++){
                  bombs[i].move();
                }
            }
    
            private function makeBomb():void{
               var b:Bomb = new Bomb();
               b.x = Math.floor(Math.random() * 100) + 50;
               bombs.push(b);
               addChild(b);
               if (Math.random() < 0.5){
                  b.makePink();
               }
            }
        
        }
        
    }
    Bomb:
    Code:
    public class Bomb extends Sprite{
    
      private var pink:Boolean;
      private var velY:int;
      private var startVelY:int = 2;
    
      public function Bomb(){
         pink = false;
         velY = startVelY;
         drawBomb(0x000000);
      }
    
      //turn this bomb pink
      public function makePink():void{
        if (!pink){
         drawBomb(0xff8888);
         addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
         addEventListener(MouseEvent.MOUSE_UP, endDrag);
         pink = true;
         buttonMode = true;
       }
      }
    
      public function move():void{
        y += velY;
      }
    
      public function isPink():Boolean{
       return pink;
      }
    
      private function drawBomb(color:uint):void{
        graphics.clear();
        graphics.beginFill(color);
        graphics.drawCircle(0, 0, 20);
        graphics.endFill();
      }
    
      private function beginDrag(e:Event):void{
        velY = 0;
        startDrag();
      }
    
      private function endDrag(e:Event):void{
        velY = startVelY;
        stopDrag();
      }
    
    }

  4. #4
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    You are very right about that, but my point is that I wanted it to work so I first experimented it with the pinkbomb, hope that helps to understand it.
    '


    But seeing your way of coding, it makes more sense and understandable what was going wrong. I will take your advice, many thanks

  5. #5
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    Ok I checked your code and I came up with a few questions.

    1. In the code you make the bomb black and the boolean pink is set to false, if the boolean is false make the pink and the pink will be set to true. The proces starts all over again because of the for loop in the main.

    But! How does it determine the color of the bomb randomly?

    2. When I click on a bomb to drag it, and leave the mouse button, it still happens to stick on my mouse without holding the mouse button. How can I fix this?

  6. #6
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    1. The only loop in Main is in moveBombs, and that's not what you're talking about. There is a Timer that executes periodically.
    Each time the timer ticks, makeBomb is called. Just for reference, here's makeBomb again.
    Code:
            private function makeBomb():void{
               var b:Bomb = new Bomb();
               b.x = Math.floor(Math.random() * 100) + 50;
               bombs.push(b);
               addChild(b);
               if (Math.random() < 0.5){
                  b.makePink();
               }
            }
    So, a new Bomb is created, then its x value is set randomly. Then we add the new Bomb to our array of Bombs and to the display. The if statement determines whether or not to make the new Bomb pink. Math.random() returns a value between 0 and 1, so half the time that value will be less than .5. So basically it's a coin toss. Half the time, we call makePink on the new Bomb.

    2. It shouldn't, but we can re-arrange things to put the mouse_up listener on the stage rather than the the Bomb. The bookkeeping to add and remove listeners gets a little more complex.
    Code:
    public class Bomb extends Sprite{
    
      private var pink:Boolean;
      private var velY:int;
      private var startVelY:int = 2;
    
      public function Bomb(){
         pink = false;
         velY = startVelY;
         drawBomb(0x000000);
      }
    
      //turn this bomb pink
      public function makePink():void{
        if (!pink){
         drawBomb(0xff8888);
         addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
         pink = true;
         buttonMode = true;
       }
      }
    
      public function move():void{
        y += velY;
      }
    
      public function isPink():Boolean{
       return pink;
      }
    
      private function drawBomb(color:uint):void{
        graphics.clear();
        graphics.beginFill(color);
        graphics.drawCircle(0, 0, 20);
        graphics.endFill();
      }
    
      private function beginDrag(e:Event):void{
        velY = 0;
        startDrag();
        if (stage){
           stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
        }
      }
    
      private function endDrag(e:Event):void{
        velY = startVelY;
        stopDrag();
        if (stage){
           stage.removeEventListener(MouseEvent.MOUSE_UP, endDrag);
        }
      }
    
    }
    I put the if statements around the event listener stuff just in case somehow the Bomb gets removed from the display. That really shouldn't happen.

  7. #7
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    I was confused, I understand te first part yes, thanks anyways.

    But I always wondered the difference between stage and the object you assign an event listener to?

  8. #8
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    The stage is the player itself. The root is the main timeline, or document class instance. When you put a listener on the stage, it'll catch events from anywhere in the swf. If you put a listener on an individual object, it will only catch events that go through that object. So by putting the mouse_up listener on the stage, it'll be triggered even if the mouse is not on the bomb. But if we had the listener on the bomb, it would only trigger if the mouse_up occurred when the mouse was over the bomb.

  9. #9
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    What do you mean by anywhere exactly?

    But when putting it on an object it will only trigger when the object is activated right?
    But the most important thing is to remove the listener so it would not stick on the mouse.

    Right conclusion?

  10. #10
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    Anywhere within the bounds of the swf, provided that the event is not stopped from bubbling up by something calling stopPropagation or stopImmediatePropagation on it. It will still not be detected if the mouse up occurs in the surrounding HTML rather than on the swf. But you can do some fancy javascript and ExternalInterface stuff to detect that if you need to.

    The term "activated" as you've used it is not clearly defined. An event listener on an object will be triggered if that object or any object that is a display decendant of it dispatches an event of the type that it is listening for (and that event actually bubbles up to the listening object). Not all events bubble, and even bubbling events can have their propagation stopped. In the usual case of mouse events, they do bubble, and nothing calls stopPropagation unless you explicitly tell it to.

    Removing any listener will not "unstick" the bomb from the mouse. The reason it's "stuck" is because its startDrag method was called. To unstick it, its stopDrag method must be called. Removing the mouse_down listener won't unstick it because startDrag was already called (or else it wouldn't be dragging), and removing the listener won't call stopDrag.

  11. #11
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    Ok it is getting clearer now. Now you mention bubbling: does that mean that when you call an enterframe, it "bubbles" because it keeps going in checking frames?

    Btw I removed the stage part in my code, else you can click anywhere ofcourse and the game would be alot more easier my meaning was to let the user click on the object it self.

    I wrote down a trick I used earlier, but I guess there are better ways to stop the startdrag. I used

    Actionscript Code:
    If (MouseEvent.MOUSE_UP)
    {
        stopDrag();
    }

    Im calling this in my constructor.

    This works, although I assume there are better ways.

  12. #12
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    No, the ENTER_FRAME event does not bubble. And that's not what bubbling means. Bubbling means that an event will first be detectable by the object that dispatches that event, then by that object's parent, then the parent's parent, etc, all the way up the display to the Stage.

    stopDrag in the constructor makes no sense. startDrag couldn't have been called on it yet, so you can't stop dragging. Also, that conditional makes no sense. MouseEvent.MOUSE_UP is a constant. It always has the same value (which is "mouseUp", though that's irrelevant). You're not testing for anything, since the string "mouseUp" will always evaluate as truthy.

  13. #13
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    But the next time it creates the object it could have been called right?

    So how can I make sure it stops dragging when the mouse is up?

  14. #14
    Will moderate for beer
    Join Date
    Apr 2007
    Location
    Austin, TX
    Posts
    6,801
    No, because the next time you create a new object, you are creating a new object. So that object's startDrag could not yet have been called.

    You make sure it stops dragging when the mouse is up by doing what I showed in the last code I posted.

  15. #15
    Senior Member
    Join Date
    Mar 2010
    Posts
    107
    Makes sense.

    Ill try my best. Thank you for the explanations and time

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center