Tile Based Movement in AS3

Hello i am still trying to create tile based movement. What i mean by that is the character can move smoothly but will always end up in the middle of a tile (just like the pokemon games). I have managed to make it work if the player uses only one key, however in combination with other keys it does not work. I was hoping someone could give me advise how to fix the code or perhaps some better/easier way to do it.
Here is my code so far (this is only for left and right key) my character movieclip has the instance name char
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.events.Event;
import fl.transitions.easing.*;
import com.greensock.*;
var pixelsMoved:Number = 0;
var pixelsLeft:Number = 0;
var tweening:Boolean = false;
var rightKeyDown:Boolean = false;
var leftKeyDown:Boolean = false;
addEventListener(Event.ENTER_FRAME,Loop);
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyPress);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyRelease);
function Loop(event:Event):void
    if (tweening == false)
        if (rightKeyDown == true)
            char.x += 1;
            pixelsMoved += 1;
        else if (leftKeyDown == true)
            char.x -= 1;
            pixelsMoved += 1;
        if (pixelsMoved >= 25)
            pixelsMoved = 0;
            pixelsLeft = 25;
function KeyPress(event:KeyboardEvent):void
    if (event.keyCode == Keyboard.RIGHT)
        rightKeyDown = true;
    if (event.keyCode == Keyboard.LEFT)
        leftKeyDown = true;
function KeyRelease(event:KeyboardEvent):void
    pixelsLeft = 25 - pixelsMoved;
    if (event.keyCode == Keyboard.RIGHT)
        if (tweening == false)
            var moveRight:TweenLite = new TweenLite(char,pixelsLeft,{x:char.x + pixelsLeft,ease:None.easeNone,useFrames: true,onComplete: resetVars});
        rightKeyDown = false;
        tweening = true;
    if (event.keyCode == Keyboard.LEFT)
        if (tweening == false)
            var moveLeft:TweenLite = new TweenLite(char,pixelsLeft,{x:char.x - pixelsLeft,ease:None.easeNone,useFrames: true,onComplete: resetVars});
        leftKeyDown = false;
        tweening = true;
function resetVars():void
    tweening = false;
    pixelsLeft = 0;
    pixelsMoved = 0;
Any help is much apreciated!

I am not sure I understand all the requirements. Also I guess you refer to pacman game - not pokemon.
In any case, here is something that works pretty smooth at 60fps. Note there are no ENTER_FRAME handlers - all animations are handled by TweenLite.
Just dump the code on a timeline in a new FLA - it is not meant to be injected into your existing code. So, this is just an independent fully functional concept. All objects are created dynamically by the script - you don't have to do anything to view/test this example.
Read comments.
import com.greensock.easing.Ease;
import com.greensock.easing.Linear;
import com.greensock.easing.Sine;
import com.greensock.TweenLite;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.ui.Keyboard;
var board:Sprite;
var tileSide:Number = 40;
var numRows:int = 10;
var numCols:int = 14;
var char:Shape;
var _currentKey:uint = 0;
var tween:TweenLite;
init();
function init():void
          drawBoard();
          configStage();
function configStage():void
          stage.scaleMode = StageScaleMode.NO_SCALE;
          stage.align = StageAlign.TOP_LEFT;
          stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
          stage.addEventListener(KeyboardEvent.KEY_UP, onKeyRelease);
function onKeyRelease(e:KeyboardEvent):void
          // if the latest processed key was not release - we block the latest pressed key
          if (e.keyCode == _currentKey)
                    _currentKey = 0;
function onKeyPress(e:KeyboardEvent):void
          currentKey = e.keyCode;
function get tile():Shape
          var shape:Shape = new Shape();
          shape.cacheAsBitmap = true;
          var color:uint = 0x808080;
          var g:Graphics = shape.graphics;
          g.lineStyle(1, color);
          g.beginFill(0xEBEBEB);
          g.drawRect(-tileSide / 2, -tileSide / 2, tileSide, tileSide);
          return shape;
function moveChar(targetX:int = 0, targetY:int = 0):void
          tween = TweenLite.to(char, 0.45, {x: targetX, y: targetY, ease: Linear.easeNone, onComplete: onTweenComplete});
function onTweenComplete():void
           * need to do that
           * a. if key is kept pressed
           * c. to override situations when another key is pressed simulataneously
          currentKey = _currentKey;
function set currentKey(value:uint):void
          var targetPosition:Number = 0;
           * key value is proccessed if
           * a. key is allowed - via switch
           * b. there is no key pressed before or ptreviously pressed key _currentKey is the same as new value
           * c. tween in not active
          if ((!_currentKey || _currentKey == value) && !tween._active)
                    switch (value)
                              case Keyboard.RIGHT:
                                        targetPosition = char.x + tileSide;
                                        if (targetPosition < tileSide * numCols)
                                                  moveChar(targetPosition, char.y);
                                                  charRotation = 0;
                                        _currentKey = value;
                                        break;
                              case Keyboard.LEFT:
                                        targetPosition = char.x - tileSide;
                                        if (targetPosition >= 0)
                                                  moveChar(targetPosition, char.y);
                                                  charRotation = 180;
                                        _currentKey = value;
                                        break;
                              case Keyboard.UP:
                                        targetPosition = char.y - tileSide;
                                        if (targetPosition >= 0)
                                                  moveChar(char.x, targetPosition);
                                                  charRotation = -90;
                                        _currentKey = value;
                                        break;
                              case Keyboard.DOWN:
                                        targetPosition = char.y + tileSide;
                                        if (targetPosition < tileSide * numRows)
                                                  moveChar(char.x, targetPosition);
                                                  charRotation = 90;
                                        _currentKey = value;
                                        break;
function set charRotation(value:Number):void
          if (char.rotation == -180)
                    char.rotation = 180;
          if (char.rotation == 180 && value == -90)
                    char.rotation = -180;
          else if (char.rotation == -90 && value == 180)
                    value = -180;
          TweenLite.to(char, 0.2 * (Math.abs((char.rotation - value) / 90) || 1), {rotation: value});
function drawBoard():void
          board = new Sprite();
          var numTiles:int = numRows * numCols;
          for (var i:int = 0; i < numTiles; i++)
                    var t:Shape = tile;
                    t.x = tileSide * (i % numCols);
                    t.y = tileSide * int(i / numCols);
                    board.addChild(t);
          board.addChild(addChar);
          addChild(board);
          board.x = board.y = 20 + tileSide / 2;
function get addChar():Shape
          var radius:Number = tileSide / 2 - 4;
          char = new Shape();
          var g:Graphics = char.graphics;
          g.lineStyle(1);
          g.beginFill(0xff0000);
          g.drawCircle(0, 0, radius);
          g.endFill();
          g.lineStyle(2);
          g.moveTo(0, 0);
          g.lineTo(radius, 0);
          g.beginFill(0x000000);
          g.moveTo(radius, 0);
          g.lineTo(radius - 10, 4);
          g.lineTo(radius - 10, -4);
          g.endFill();
          tween = new TweenLite(char, 1, null);
          char.cacheAsBitmap = true;
          return char;

Similar Messages

  • Tile based movement in flash as3

    Hello i am currently working on the engine for a tiled based game. I have set up the map using a 2 dimensional array. Movement wise i have just increased/decreased the x/y position of my characer by the same amount of pixels as my tiles. Anyway of course this does not look good as my character is just "teleporting" to the next tile. Perhaps anyone can help me how to make some smooth movement and still ensure that my character will end up in the middle of a tile (Just like in the pokemon games).
    Any help is much appreciated - John

    Use a tween engine:
    http://www.greensock.com/

  • Best way to do a tile-based map

    Hello everybody-
    This should be a simple thing but I just can't get it to work. I'm making a tile-based top-down online rpg (application, not applet), and I pretty much have most of it done except I can't get the map to display and scroll right. i will admit that java graphics isn't really my thing, but i just can't get it. Its been so frustrating that i actually quite develpment on my game and quit for awhile, but i decided to try again. What I have is an array if images that make up the map, and then i manipulate the array depending where the character is so i only draw the tiles necessary. what i want to do is to combine all the tiles i need for the particular position, draw that image to the screen (so i don't have to draw each tile individually to the screen). then i could move that large image depending where the character moved, and add tiles to it depending on which way the character moves. I just can't get it to work however. I've looked at double-bufferning posts and that gave me some ideas, but not enough for my particular situation. if anybody has any experience in this i would be more than greatful. thank you

    I know exactly what you are talking about, I had your problem a while back when I was doing mobile phone games.
    To reduce the number of cell draws needed, cells were only drawn when at the edges of the view area. (all other cells were maintained from the previously drawn frame.)
    It gets pretty complicated, but it will work - stick with it.
    I would post some code - but I don't have it anymore - and it was pretty specific to J2ME MIDP API (java mobile phone).
    p.s. When I did it, I had to include several additional optimisation, these made it incredibly complex :(
    I will try to describe it, but without pictures, It will probably be in vain. (don't worry if you don't understand it :P)
    here is the summary of the logic :-
    the backbuffer had dimensions SCREEN_WIDTH+CELL_WIDTH*2, SCREEN_HEIGHT+CELL_HEIGHT*2 (I effectively had a border that was CELL_WIDTH wide, and CELL_HEIGHT tall.)
    this meant new cells only had to be drawn every time the view area passed over a cell boundary.
    however, doing this, meant it was super smooth until it hit a cell boundary, at which point it had to draw all the cells in the newly exposed column and/or row - which caused a jerk.
    To get around this, I devised a speculative rendering, where by the next column/row was pre-rendered over a series of game frames.
    (each column/row had its own buffer into which the pre-rendering was done)
    On average 2-4 times as many edge cells had to be rendered than needed, but, because the camera moved slowly, this could be distributed over approx. 10 game frames.
    By distributing the rendering of the edge cells over a number of game frames, I hoped to remove the jerk experienced as the camera crossed a cell boundary.
    The system worked... ish... but I never finished it :(
    basically, these were crazy optimisations that were only necessary because I was developing for mobile phones.
    On mobile phones the speed of rendering is relative to the number of draw calls, NOT the actual area of the screen being repainted.
    e.g.
    fillRect(0,0,50,50)
    fillRect(0,50,50,50)
    will take almost twice as long as
    fillRect(0,0,100,100)
    even though you are only painting 1/2 the area.

  • Tile-based map and A-star help?

    I am working on a tower defense type game. A while ago I posted asking about maze logic and was kindly directed towards A-star pathfinding. It is perfect. I understand the concept and it makes sense. Now the problem I am having is how to do the tile-based map? I'm having a hard time wrapping my head around it. I just want to do a straight square map comprised of squares. I realize a 2D Array would probably be the best way just such as:
    int[][] map = new int[100][100]
    where there would be 100 x 100 tiles. I can then populate the array with numbers ie 0 = walkable, 1 = unwalkable. I can have my A* algorithm return the set of tiles to move to.
    My problem is that I don't want my game to be in pixels and I'm having a hard time understanding how to make the game appear tile based and large enough to be playable? ie. 1 tile = 30x30 pixels. If we are looking at it in terms of model and view, I understand the model part, but I am having a hard time translating to the view? How do I create a tile based view so that the user can only place towers on a tile(the mouse click location could be any point inside the tile)? Also, how would I keep the enemy units moving smoothly between tiles and not just jumping to the center of each tile?
    I got some great advice last time and any more advice or points in a good direction would be greatly appreciated.

    The reason to distribute your maze into nodes (tiles) is that pathfinding is slow, so you want to eliminate any notion of screen dimensions (pixels, inches, etc.) from A*. For all purposes, your maze is 100x100 pixels; any given object can choose between 100 horizontal and 100 vertical values.
    how would I keep the enemy units moving smoothly between tiles and not just jumping to the center of each tile?Although your units may only have 100x100 nodes to consider, you can still animate them walking between each adjacent node on the path. Remember that the pathfinding (per tier) will occur before anything actually moves.
    Still, this could look funny with only 100 nodes per axis. Units should use the shortest path that’s visible to them, and turning several degrees at each node will look choppy. So. I list three potential solutions here:
    &bull; Increase the number of nodes (the “accuracy”). Speed may be an issue.
    &bull; Use path smoothing algorithm. I haven’t seen your circumstance, but I would generally recommend this.
    &bull; Use multi-tiered/hierarchical pathfinding. This is probably more complex to implement.
    Note that although the second and third options are distinct, they may coincide (some smoothing algorithms use multiple tiers). Googling for ‘pathfinding smoothing’ returned many results; this one in particular looked useful: [Toward More Realistic Pathfinding|http://www.gamasutra.com/features/20010314/pinter_01.htm]
    How do I create a tile based view so that the user can only place towers on a tile(the mouse click location could be any point inside the tile)?If objects can be placed at arbitrary points, then A* needs to deem nodes impassable (your array’s 1) based on the objects placed in them. You have to be careful here and decide whether entire nodes should be ignored based on tower’s partial presence; for instance:
    |====|====|====|====|====|
    |====|====|====|===+|+++=|
    |====|====|====|===+|+++=|
    |====|====|====|====|====|
    |0~0=|====|====|====|====|pixels: = ; node dividers: | (and line breaks for vertical) ; tower: +
    The tower only covers ¼ of the node at (3, 3); should you eliminate it? Five solutions are obvious:
    • Ignore any node with any chunk of a tower in it.
    • Ignore any node entirely covered by a tower.
    • Ignore any node whose center is covered by a tower. This won’t work with multi-tiered pathfinding.
    • Ignore any node that has a tower covering any point the units are required to pass through. This will work with multi-tiered pathfinding.
    • Using multi-tiered pathfinding, consider only consider the sub-nodes that aren’t covered by a tower.
    I realize a 2D Array would probably be the best way just such as
    int[][] map = new int[100][100]
    For starters, if only want two values—passable and impassible—then a boolean would be better. But I would recommend against this. I’d bet you could write some OO code specific to your situation. You might want to use terrain costs, where nodes exist that A* would prefer over others.
    I hope I answered some of your questions. Let me know if you have more—or if I didn’t.
    Good luck.
    —Douglas

  • How to animate from a png tile based image file

    Hi all,
    I would like to know is there any way to animate from a tile based .png image file? I have multiple images in 1 png file having slight changes in each image, which if cropped and put into layers one over the other, will give the feel of animation or a character moving or walking etc...
    I want to know can we do that kind of animation in flash as we do it in C++ or Java and how can we do it.
    Any help will be highly appreciated.
    Thank you
    Shanz - Iceheros

    I want to use action script to externally call/access  the png file with url request and url loader and animate the images from the tile based png image file.
    Anybody know how to do this in flash with as3.
    Here is the image for example:
    i want to animate this images and call it externally and access each tile 1 after another.
    Any Help???
    Thanks,
    Shanz - Iceheros

  • Smooth walking on tile based map system

    Hello,
    I am developing a small game which requires the use of a map system. I chose to make that map system work upon a tile-based system. At the moment, each tile is 32x32, and I contain 24x20 tiles on my map.
    A walking system is also required for this game I'm developing, so I ran into some issues with making the loaded sprite walk "smoothly". At the moment, it jumps from tile to tile in order to walk. This makes it seem very unrealistic. I have tried many different ways to make the walking "smoother", but it requires me to change my tile's size in order to accommodate the sprite's size. This would not be an issue if I only used the same sprite in the game, but since I load different sprites which contain different measurements, I do not know how to make my walking system accommodate all of the sprites in order to make the walking realistic.
    I am not requesting any code whatsoever, simply ideas.
    Thank you

    If your image is opaque, then it may draw the edges around itself, but wouldn't this be a problem wether it were completely contained within a tile or not? If the image has transparency, then it doesn't matter if it's drawn as a rectangle, it would still appear to be contained only by its outline.
    If you're using a back-buffer (which I highly recommend if there is going to be animation or movement onscreen), then you may need to specify the type for the BufferedImage that you use as a buffer, I always use TYPE_INT_ARGB to make sure I have Alpha values (transparency).

  • Effecient tile-based game setup

    Hello i am working on the engine for a tile based game, i have set up a two dimensional array with the number 1 representing a tile, and the number 0 representing an empty space. Currently i am using the following code which does work, but it is no very effecient because there are too many movieclips on the stage, which is causing my game to run at a lower framerate.
    function prepareGame():void
        for (var y:int = 0; y<mazeHeight; y++)
            for (var x:int = 0; x<mazeWidth; x++)
                if (myMaze[y][x] == 1)
                    var cell:MovieClip = new mc_tile();
                    cell.x = ts * x;
                    cell.y = ts * y;
                    addChild(cell);
    So my question is how do i optimize this code? If i could somehow make flash view all the movieclips as one big bitmap i guess that would solve the problem but i need some help.
    Any help is appreciated thank you!

    Here is an example of scrolling tiles (just paste the code on timeline).
    Background takes only stage dimensions but the impression is that it scrolls indefinitely.
    import flash.display.BitmapData;
    import flash.display.Graphics;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    var board:Sprite;
    var bitmapData:BitmapData;
    var appendBitmapData:BitmapData;
    var copyRect:Rectangle;
    var zeroPoint:Point = new Point();
    var targetPoint:Point;
    var speed:Number = -1;
    init();
    function init():void
              drawBoard();
              setGeometry();
              addEventListener(Event.ENTER_FRAME, animate);
    function drawBoard():void
              board = new Sprite();
              var tileInstance:Sprite = tile;
              bitmapData = new BitmapData(tileInstance.width, tileInstance.height);
              bitmapData.draw(tileInstance);
              var g:Graphics = board.graphics;
              g.beginBitmapFill(bitmapData, null, true);
              g.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
              addChild(board);
    function setGeometry():void
              appendBitmapData = new BitmapData(Math.abs(speed), bitmapData.height, true, 0x00000000);
              copyRect = new Rectangle(0, 0, Math.abs(speed), bitmapData.height);
              targetPoint = new Point(bitmapData.width - 1, 0);
    function animate(e:Event):void
              bitmapData.lock();
              appendBitmapData.copyPixels(bitmapData, copyRect, zeroPoint);
              bitmapData.scroll(speed, 0);
              bitmapData.copyPixels(appendBitmapData, copyRect, targetPoint);
              bitmapData.unlock();
    function get tile():Sprite
              var s:Sprite = new Sprite();
              var g:Graphics = s.graphics;
              g.lineStyle(2, 0x004000);
              g.beginFill(0x009700);
              g.drawRect(1, 1, 80, 50);
              return s;

  • Tile Based Collision Detection

    I am following Tonypa's Tile Based Tutorials and I have to
    say, they are great. He covers everything needed, except for one
    thing I am troubled on - Refering to Tutorial 9,
    http://www.tonypa.pri.ee/tbw/tut09.html,
    Stupid Enemy, instead of an enemy I want to make this a NPC who
    walks around in a village. So what do I do to make it so that I, or
    the char, doesn't walk right over the enemy/NPC? I am trying to
    develop an RPG, and it would look silly to have the character walk
    on top of the NPC. Can someone provided a snippet on how to make a
    collision detection with the NPC and not walk on top/under the NPC?
    One last favor to ask: What if I want to talk to the NPC if I
    am within a half tile? Would anyone be willing to share info on how
    this as well?
    Thanks a bunch in advance

    Ok, let me see if I get the read correct here: you have your scenery objects as tiles and when moving your players/NPC's through the scenery you are not scrolling the background as you go, but when you get to s certain point you want to scroll the tiles of the background also, so you can have new scenery cycle in as needed an still have the tiled background objects and new tiled background objects work for collision detection.
    If my take on your project is correct, then you have to make your tiles addressed with relative addressing formulas as you'll probably need to do with your sprites also.
    So the way this will go is that you have to make an offset and add them into your formula based on your character position. Then based on your character position you can choose to scroll your tiles left, right, up, down or what ever you choose to support. As a tile falls fully off the screen, you can dispose of it or cycle back through depending on how you implement your background.

  • Tile based pathfinding

    Allright i am about to start working on something that i have never tried before. I am making a tile based game which is set up with a two-dimensional array.
    0 in the array represents wall tiles which aren't walkable.
    1 in the array represents path tiles which can be walked on.
    I would like to add some enemies to the game which i want to have following the character. The enemies must follow the character by walking on the shortest route possibly. I have tried looking into path-finding but it seems quite complex. If anyone has some advice on how i would go about doing this, i would very much love to hear. Maybe if someone can recommend a good tutorial that would be nice.
    Thanks in advance!

    Here's your typical A* pathfinding explained:
    http://www.raywenderlich.com/4946/introduction-to-a-pathfinding

  • Moving Background Based Mouse Movement (Parallax) AS3

    I found this AS2 tutorial online but I'd like to achieve this in AS3. I tried transcribing but the  setProperty is throwing me off. Thanks
    //AS 2 parallax code
    stageWidth = Stage.width;
    speed1 = 20;
    speed2 = 19;
    mc1Width = front_mc._width;
    mc2Width = back_mc._width;
    mc1X = front_mc._x;
    mc2X = back_mc._x;
    lock_scroll = false;
    _root.onEnterFrame = function () {
        if (!lock_scroll)
            scroll_mc();
    function scroll_mc() {
        var xdist = _xmouse-(stageWidth/2);
        mc1X += -xdist/speed1;
        mc2X += -xdist/speed2;
        if (mc1X>=0) {
            mc1X = 0;
        if (mc1X<=stageWidth-mc1Width) {
            mc1X = stageWidth-mc1Width;
        if (mc2X>=0) {
            mc2X = 0;
        if (mc2X<=stageWidth-mc2Width) {
            mc2X = stageWidth-mc2Width;
        setProperty("front_mc", _x, mc1X);
        setProperty("back_mc", _x, mc2X);
    //create an empty mc container for content to display
    createEmptyMovieClip("content_box", 200);
    content_box._x = 195;
    content_box._y = 92;

    Ok I added that line of code. But my background isn't moving...
    var stageWidth:Number = stage.width;
    var speed1:Number = 20;
    var speed2:Number = 19;
    var mc1Width = front_mc.width;
    var mc2Width = back_mc.width;
    var mc1X:Number = front_mc.x;
    var mc2X:Number = back_mc.x;
    var lock_scroll:Boolean = false;
    stage.addEventListener(Event.ENTER_FRAME, scroll_mc);
    function scroll_mc(event:Event):void
            //if (!lock_scroll)
                    var xdistance = mouseX-(stageWidth/2);
                    mc1X += -xdistance/speed1;
                    mc2X += -xdistance/speed2;
                    if (mc1X>=0)
                        mc1X = 0;
                    if (mc1X<=stageWidth-mc1Width)
                        mc1X = stageWidth-mc1Width;
                    if (mc2X>=0)
                        mc2X = 0;
                    if (mc2X<=stageWidth-mc2Width)
                        mc2X = stageWidth-mc2Width;
                    back_mc.x=mc1X;
                    front_mc.x=mc2X;

  • Attach movie in as3

    Hey all, I'm fairly new to flash, but I can do a few things,
    I had a
    good flash program going in as1, which I'm trying to convert
    to as3.
    I had asked on irc for some help, but it was touching on
    subjects I have
    not covered on as, and even after looking up and applying,
    its causing
    countless problems.
    1) My application receives information currently from echoed
    information
    from a db onto a html page, which flash is able to feed in
    e.g. (echo
    &var+rowvar+&).
    I'm considering xml although I'm unsure about benefits or
    anything
    2)in as1 my application could simple do a for loop with the
    number being
    passed in via the number of rows in the database which was
    echoed onto
    the page then fed into flash.
    Do for loops act the same in as3?
    3)I was attaching a movie clip multiple times, which I need
    to get to
    act all independent of each other, so each one needs its own
    name, as1
    this was possible via "_root.attachMovie("button","btn"+i,
    100+i);"
    and this is where the main problem is, as I was asking about
    this,
    attachmovie no longer works, and I got told to sort out
    "linkage" which
    I have done, then setting up class and using addchild. which
    I have
    tried... but it does not work and I cannot get around.
    reading up on it, documents say addchild should enable the
    object to be
    displayed. which for me isnt happening.
    Here are the list of problems I have been getting:
    -An ActionScript file must have at least one externally
    visible
    definition. so I looked it up, and I figured I have to put up
    a
    package and public class (athough I do not understand
    class's)
    which resulted in the error
    -TypeError: Error #1006: addChild is not a function. at
    global$init()
    which sounds great...
    messing around got me to
    -5008: The name of definition 'test' does not reflect the
    location of
    this file. Please change the definition's name inside this
    file, or
    rename the file. z:\location\index.as
    so I changed the class "test" to "index" where I encountered
    more
    problems...
    [code]
    var page1:page_mc = new page_mc ();
    this.addChild(page1);
    [/code]
    [code]
    package
    import flash.display.MovieClip;
    public class index extends MovieClip
    public function index()
    trace('lol');
    [/code]
    and by the way, I have tried using addchild on frame1 of the
    fla, with
    no results.
    I'm sure I'm missing something at the biginning because
    looking up every
    problem and getting more errors seams silly for something
    that was so
    easy in as1, that I would need so much code to stop problems
    of 1
    function..)
    Thanks in advance
    Slpixe

    Slpixe,
    > 1) My application receives information currently from
    > echoed information from a db onto a html page, which
    > flash is able to feed in e.g. (echo
    &var+rowvar+&).
    I'm with ya so far.
    > I'm considering xml although I'm unsure about
    benefits>
    > or anything
    If you're passing in a handful of name/value pairs, you
    probably don't
    need XML. By what you're describing, it sounds like you're
    using FlashVars,
    or passing these variables into the SWF as a query in the
    HTML. The benefit
    to FlashVars is that the SWF has access to these values
    immediately upon
    load. You don't have to take measures to load the data
    yourself, and then
    to respond to onLoad events, and so on -- they're just
    magically there.
    Prior to AS3, those variables are scoped to the main
    timeline, as if you
    had declared them there in frame 1. In AS3, you can use the
    same technique,
    but the variables are scoped as properties of the parameters
    property of a
    LoaderInfo instance associated with the main timeline. Sounds
    like a
    mouthful, but all it means is that you have to path to the
    incoming
    variables:
    this.loaderInfo.parameters.myVar1;
    this.loaderInfo.parameters.myVar2;
    this.loaderInfo.parameters.myVar3;
    If you have tons of hierarchical data, or data that don't
    lend
    themselves to simple name/value pairs, XML will help
    considerably. Of
    course, you'll have to load the XML, then navigate among your
    nodes to
    retrieve the information, but AS3's E4X syntax makes this
    much easier than
    it was to do the same with XML in AS1/AS2.
    > 2)in as1 my application could simple do a for loop with
    the
    > number being passed in via the number of rows in the
    database
    > which was echoed onto the page then fed into flash.
    > Do for loops act the same in as3?
    Yes.
    > 3)I was attaching a movie clip multiple times, which I
    need to
    > get to act all independent of each other, so each one
    needs
    > its own name, as1 this was possible via
    "_root.attachMovie
    >("button","btn"+i, 100+i);"
    Okay.
    > and this is where the main problem is, as I was asking
    about this,
    > attachmovie no longer works, and I got told to sort out
    "linkage"
    > which I have done,
    Meaning, instead of a linkage identifier, a linkage class.
    > then setting up class and using addchild. which I have
    tried... but
    > it does not work and I cannot get around.
    Heh. Well, it does work, I promise you that. ;) So it should
    just be
    a matter of stepping through the approach you're using to see
    what's going
    awry when.
    > reading up on it, documents say addchild should enable
    the
    > object to be displayed. which for me isnt happening.
    The addChild() method originates with the
    DisplayObjectContainer class,
    which means you need an instance of that class as a reference
    when you
    invoke the method. Makes sense, right? You couldn't
    instantiate an an
    array, for example, and do this:
    var arr:Array = new Array();
    arr.addChild(someVisualObject);
    ... because the Array class doesn't support the addChild()
    method. It's the
    DisplayObjectContainer class that does, so you can only add
    objects to the
    display list of an object that supports display lists.
    Fortunately, the main timeline is (usually) an instance of
    the MovieClip
    class, and MovieClip inherits much of its functionality from
    the
    DisplayObjectContainer class. Even when the main timeline is
    configured as
    a sprite, it still inherits the functionality in question,
    because the
    family tree goes like this: DisplayObjectContainer -->
    Sprite -->
    MovieClip.
    So all you really need, in theory, is to invoke that method
    on any movie
    clip symbol's instance name, or on a reference to the main
    timeline, and
    your object should show up.
    > Here are the list of problems I have been getting:
    > -An ActionScript file must have at least one externally
    visible
    > definition. so I looked it up, and I figured I have to
    put up a
    > package and public class (athough I do not understand
    class's)
    I'm assuming, then, that your code -- at least, currently --
    all appears
    in keyframes?
    > which resulted in the error
    > -TypeError: Error #1006: addChild is not a function. at
    global$init()
    > which sounds great...
    Hrrrm.
    > messing around got me to
    > -5008: The name of definition 'test' does not reflect
    the location of
    > this file. Please change the definition's name inside
    this file, or
    > rename the file. z:\location\index.as
    So then, it sounds like you're putting your code inside a
    file named
    index.as, which means (by the rules of how Flash operates)
    that you're
    defining a class called index. If you're using the class
    keyword to define
    this class, it means you'll have to use the word "index" as
    the name of your
    class, because class names have to match the names of the
    files in which
    they're defined.
    > so I changed the class "test" to "index" where I
    encountered more
    > problems...
    >
    > [code]
    > var page1:page_mc = new page_mc ();
    > this.addChild(page1);
    > [/code]
    To me, it looks like you've put these first few lines ahead
    of your
    package and class declarations. That's now how class files
    work. All of
    your code must be sandwiched inside the package or (usually)
    class
    declaration. Otherwise, you're not writing a class at all
    (which is fine)
    ... but then, you need to use the include directive (just
    like AS1/AS2's
    #include), which simply pulls the code in at compile time as
    if it were
    typed in a timeline keyframe.
    In this code:
    > [code]
    > package
    > {
    > import flash.display.MovieClip;
    >
    > public class index extends MovieClip
    > {
    > public function index()
    > {
    > trace('lol');
    > }
    > }
    > }
    > [/code]
    You're defining a class named index that extends MovieClip.
    That means
    index *is* a movie clip, which means it has available to it
    all the
    functionality defined by the MovieClip class. If you were to
    invoke
    addChild() from some method *inside* this class declaration,
    it would work
    ... because the addChild() method is supported by movie
    clips.
    > and by the way, I have tried using addchild on frame1 of
    the fla,
    > with no results.
    Mixing and matching is fine. You can indeed use timeline
    code alone in
    AS3, or class code alone, or a combination of both. I wonder
    if you're just
    "in too deep" with the file you have? I recommend you brush
    away the
    distractions and start a fresh, new FLA file.
    In that file, draw a quick shape -- just a circle, say --
    and convert it
    to a movie clip. Right-click on that symbol in the Library
    and choose
    Linkage. Select "Export for ActionScript" and give this thing
    a linkage
    class (for example, Circle).
    When you click OK to close the dialog box, Flash will warn
    you that no
    such class (Circle) exists, and offers to write that class
    for you. Click
    OK.
    Now enter frame 1 and use the Actions panel to type these
    lines:
    var orb:Circle = new Circle();
    addChild(orb);
    The variable orb (just an arbitrary name) is typed as Circle
    -- which is
    the class Flash just wrote for you -- and set to an instance
    of that class.
    In the Linkage dialog box, you will have seen that the Circle
    class extends
    MovieClip, so this isn't much different from instantiating a
    new movie clip
    in AS3.
    Finally, the DisplayObjectContainer method, addChild(), adds
    your Circle
    instance to the display list of the main timeline. You could
    precede the
    addChild() reference with the "this" keyword, but even
    without it, Flash
    understands that you're refering to the timeline in which
    this code appears.
    And because that timeline is a descendent of the
    DisplayObjectContainer
    class, the method works.
    David Stiller
    Co-author, The ActionScript 3.0 Quick Reference Guide
    http://tinyurl.com/2s28a5
    "Luck is the residue of good design."

  • Hide/Show a button on a tile, based on the tileset you're in.

    Hey,
    I made a new tileset Z_CustomerPlan, it has an existing tile in it, capshort1.
    I added a button to this existing tile capshort1, named Z_BTNPreviewAll.
    But this button should ONLY be visible when in the new tileset Z_CustomerPlan because capshort1 is used in some other tilesets.
    i tried to do this with the following code in the onload event of capshort1:
    if not mcore.uftileset = "SZ_CustomerPlan" then
         ctrlZ_BTNPreviewAll.visible = false
    end if
    but this isnt working, it makes the button invisible on all tilesets, including Z_CustomerPlan.
    So im trying to show/hide the button based on the tileset... is this the right way?
    Some help would be nice.
    Cheers,
    Maarten

    Hey Vadim,
    After an intensive investigation i came to the following conclusion...
    if not mcore.uftileset = "SZ_CustomerPlan" then
         ctrlZ_BTNPreviewAll.visible = false
    end if
    does not work, BUT..
    if not mcore.uftileset = "sZ_CustomerPlan" then
         ctrlZ_BTNPreviewAll.visible = false
    end if
    ..does work
    can you spot the difference?:)
    apparently it HAS to be a little s
    just glad its working now, i put it in the beforeload like you suggested, thx for the tip
    cheers,
    Maarten

  • Strange behaviour of .swf movies - AS2/AS3

    Hello from Italy,
         this is my first post and I think I need some help from the experts...
         I am putting together an interactive Flash movie which is made of several different small movies. For the sake of clarity, I'll call them A.swf, B.swf, ..., Z.swf. The movies are launched from each other depending on certain buttons I've implemented.
         The first one, A.swf, is actually a sort of "main menu": it grants access to all the other movies and it is also the point of return from them when a certain button is pressed.
         Important: All the movies are scripted in AS3, except for the last one which, for a number of reasons, is scripted in AS2.
         The return from any (but the last) movie to the first, say B.swf to A.swf, is implemented like this:
    function eventResponseSole(event:MouseEvent):void {
    var myLoader:Loader = new Loader();
    addChild(myLoader);
    var url:URLRequest = new URLRequest("A.swf");
    myLoader.load(url);
    sole_btn.addEventListener(MouseEvent.CLICK, eventResponseSole);
         This is, of course, AS3.
         The last movie, which is scripted in AS2, returns to A.swf like this:
    luna_btn.onRelease = function() {
    loadMovie("A.swf", _root);
         The strange behaviour is this: if I launch Z.swf and navigate with the proper button up to A.swf, everything works. But if I launch A.swf, navigate to Z.swf and attempt to return, this doesn't work. There are no problems, instead, moving up and down between movies scripted in AS3, that is with the first bit of code I've pasted. My guess is that the syntax in AS2 is correct, but something stops A.swf from "launching itself" when the control is transferred to Z.swf, but the movie is launched in the original window. Is this diagnosis reasonable? And if so, would someone kindly provide a way out of this? Re-doing Z.swf in AS3 is not an option, I'm afraid, it will have to stay as it is. I also have to add I've tried some solutions by setting _lockroot, but this doesn't seem to work.
         Many thanks in advance!
         Marco Olivotto

    Mixing AS2 into AS3 is not without stipulations... and I am no expert on translating those stipulations, but here is what the Flash documentation says regarding the matter... the third paragraph may be significant to your case:
    - ActionScript 3.0 code can load a SWF file written in ActionScript 1.0 or 2.0, but it cannot access the SWF file's variables and functions.
    - SWF files written in ActionScript 1.0 or 2.0 cannot load SWF files written in ActionScript 3.0. This means that SWF files authored in Flash 8 or Flex Builder 1.5 or earlier versions cannot load ActionScript 3.0 SWF files.
    The only exception to this rule is that an ActionScript 2.0 SWF file can replace itself with an ActionScript 3.0 SWF file, as long as the ActionScript 2.0 SWF file hasn't previously loaded anything into any of its levels. An ActionScript 2.0 SWF file can do this through a call to loadMovieNum(), passing a value of 0 to the level parameter.

  • Load Movie in AS3 for cd-rom output

    I have a .project with multiple >SWF's, which links to many other flash movies...I want to open each of the movies
    in it's own window, but not in a browser. (CD-rom output). The complete project is like a book with PREVIUS and NEXT buttons. Each one unloads the current  SWF and opens a new one.  .
    I have used the following script in AS2 with great success. However I haven't found the way to achieve the same result in AS3. Here is my AS2 script.
    on (release) {
    loadMovie("CD09.swf", _root);
    I know that this is very basic but I can not write a script to achieve the AS2 Result.
    Your help is very appreciated.

    I appreciate your input. Wrote the code as follows: (remove the "private" because the code is in the timelinI appreciate your input. Wrote the code as follows: (remove the "private" because the code is in the timeline)
    //back_btn button function
    back_btn. addEvent Listener(MouseEvent.CLICK,mouseClick);
    function mouseClick(event:MouseEvent):void {
    var _content:DisplayObject;
    function loadContent(content:String):void {
         if(_content != null){
            removeChild(_content);
            _content = null;
          var loader:Loader = new Loader();
          loader.load(new URLRequest(content));
          _content = addChild(loader);
         loadContent("CD09.swf");
    The parent file loads but when pressing the back_bth. button to load the new file NOTHING HAPPENS.
    I have been trying to solve this issue for a long time and I am sure we are almost there. Your kindness is very appreciated!

  • Problem going to fullscreen after loading AS2 movie into AS3

    I've got a loader movie that is written in AS3, and
    fullscreen is enabled. I have a context-menu fullscreen trigger and
    a keypress fullscreen trigger built into the loader movie. When I
    load an AS3 movie or an AS1 movie through the loader movie, I can
    go to fullscreen without problems. When I load the AS2 movie, I
    cannot.
    Does anyone have an idea why this might be? I'm struggling.
    Thanks in advance.

    Thanks for your help, but as said ("But also using a
    separated second loader to load the second file is not working.")
    even when using a second loader (with a different name) the second
    file loaded will not work.
    I'm removing any EventListener from the first loader,
    unloading and then nulling it.
    But to me it seems, that the first content is not garbage
    collected and because of that, even when loaded with an other
    loader the first loaded swf-file interferes with the second.
    I came to this conclusion, because the first loaded swf-file
    is still working after trying to load the second file. And just
    more weird: the first loaded file is in the same state and also
    after closing the Flash-Player.
    You can see it for yourself: download the testcase. Start the
    testcase.swf. Load a contentfile. Skip a few pages. Quit the Flash
    Player. Start the testcase.swf again and load the same contentfile.
    You will see it's at the same position like before quiting the
    Player.
    And I can't help, but that seems like a bug to me...

Maybe you are looking for

  • Where can I get Adobe Photoshop Elements *5*?

    I own a license for Photoshop Elements version 5, and tech support says it is no longer available. Does anyone have a source for this application? I have the license but cannot find the executable that I downloaded and purchased from Adobe. On the ot

  • Time Stamp, read from filename and change automatically

    Hi, while converting to an format (video monkey) which can be read by iMovie the files lost the propper time stamp. However, date and time is still part of the filename. Is there an option to change date and time within iMovie or any other app based

  • Opening .xls .doc and .ppt files

    Sorry for the stupid question, but how do i set it so that when I click on one of the files I do not get a message saying that my Microsoft 30 day trail has expired? I want it to automatically open into an appleworks application. Ta

  • Have old G4 Running OS 10.4.10 but want OS 9.1 back!!!!

    I have an old G4 450Mhz PowerPC which used to run 9.1 and I have the disc. When I purchased a new system, I installed OS 10.4.10 on the old G4 as well. Now I have some programs that I need 9.1 in order to run. When I go to install 9.1 from the disc,

  • Simple VM invocation from C++

    Hello, I have read about using Java as some kind of "scripting language" in computer games. The Game Vampire 2 uses this, and they had very positive experience with this, as told in an article on gamasutra.com. I want to try this too. I already searc