Search code examples
actionscript-3flashrect

How to prevent a Rect from moving from its position when decreasing width


I seem to be having problems with rectangles moving from their assigned positions when all I want to do is decrease their width. A game I'm working on simulates an explosive with a fuse. The fuse decreases in size as a clock counts down to 0. I think the problem has to do with local coordinates vs. global coords, but I'm not sure how to rectify the problem. Here is some code:

//fuse
_fuse = new Sprite();
_fuse.graphics.beginFill(0x000000);
_fuse.graphics.drawRect(630, 340, (_fuseCounter / _fuseWidth) * 120, 20);
_fuse.graphics.endFill();

And here is where I decrease its width each frame:

//decrease fuse to give the player a visual of urgency.
_fuseCounter--;         
_fuse.width = (_fuseCounter/ _fuseWidth) * 120;

Nowhere in my code does the x position of the fuse change. Aside from this one issue, the rect functions exactly how I want it to. Any help with this issue is appreciated.


Solution

  • Your problem is you're drawing your rect at 630, 340 and then reducing the width around it.

    Think of it like this

    0                    100
    -----------------------
    |                     |
    |          -----      |
    |         |     |     |
    |          -----      |
    |                     |
    |                     |
    -----------------------
    

    When you reduce the width you're essentially pulling the left edge of the outside movieclip towards the right edge, scaling the nested content as you go. Resulting in something like this

    0                  75  
    -------------------
    |                 |
    |      ---        |
    |     |   |       |  
    |      ---        |
    |                 |
    |                 |
    -------------------
    

    So to get around this you could nest. Add a new sprite to _fuse and scale that

    var s:Sprite = new Sprite();
    s.x =630;
    s.y = 340
    s.graphics.drawRect(0, 0, (_fuseCounter / _fuseWidth) * 120, 20);
    fuse.addChild(s);
    

    And then scale s.width

    If you don't want to nest you could also just do a graphics.clear() and redraw the rect to the new, smaller width