Creation of a game like String Avoider tutorial

A really interesting "avoidance game" that was made in those days is String Avoider. The author of this "More than 1 million views" game in Newgrounds explains it in 12 words: "Avoid colliding with walls and guide your string through each unique level".

String avoider

And that's it. The aim of the game is guiding your string through some levels without touching the walls.

It's very similar to the ball game I am discussing in this site, but this time the ball is controlled by the mouse and has a "tail" that responses in a very "real life" way.

Something very hard to code, you may say. It's not that hard to reproduce a string movement in Flash, even if the built-in string class does not help us...

(laugh)

... but let's start with the tutorial.

The string

A string is made of two objects: the head and the tail. The player will control the head, while the tail will follow the head. That's it.

So, the first thing to do is the creation of the head. The picture below shows how to draw, position and link the head

head creation

Then in main scene first frame simply drop this actionscript

ACTIONSCRIPT:
  1. tail_len = 2;
  2. tail_nodes = 100;
  3. nodes = new Array();
  4. _root.attachMovie("the_head", "the_head", 1, {_x:250, _y:200});
  5. _root.createEmptyMovieClip("the_tail", 2);
  6. for (x=1; x<tail_nodes; x++) {
  7.     nodes[x] = {x:the_head._x, y:the_head._y};
  8. }
  9. the_head.onEnterFrame = function() {
  10.     this._x = _root._xmouse;
  11.     this._y = _root._ymouse;
  12.     the_tail.clear();
  13.     the_tail.lineStyle(2, 0x00ff00);
  14.     the_tail.moveTo(the_head._x, the_head._y);
  15.     nodes[0] = {x:the_head._x, y:the_head._y};
  16.     for (var x = 1; x<tail_nodes-1; ++x) {
  17.         rotation = Math.atan2(nodes[x].y-nodes[x-1].y, nodes[x].x-nodes[x-1].x);
  18.         pos_x = nodes[x-1].x+tail_len*Math.cos(rotation);
  19.         pos_y = nodes[x-1].y+tail_len*Math.sin(rotation);
  20.         nodes[x] = {x:pos_x, y:pos_y};
  21.         the_tail.lineTo(pos_x, pos_y);
  22.     }
  23. };

Line 1: Defining tail_len variable at 2. What is tail_len? It's the length in pixels of the fixed part between two nodes.

Line 2: Defining tail_nodes as the number of nodes that will contain the tail.

Time to give some explication: in real world, a string can bend in any of its points. In flash world, we do not want it because it will use too much computer resources and we do not need it because it's just a game. So, if we want a string 200 pixels wide, we can use the "real world" method defining tail_len at 1 and tail_nodes at 200, or we can simplify computer's work setting tail_len at 2 and tail_nodes at 100. Just remember that tail_nodes*tail_len = real tail length for high values of tail_nodes.

Line 3: Declaration of the array where will store all nodes positions

Line 4: Attaching the "head" movie on the stage positioning it in middle of it.

Line 5: Creation of an empty movie clip called "tail" that will contain the tail of the string

Lines 6-8: Cycle that creates all nodes positions. Their starting positions, defined as coordinates, at the beginning are equals to head's _x and _y coordinates

Line 9: Function to be executed at every frame

Lines 10-11: Placing the head at current mouse x and y positions

Line 12: Clearing the tail movieclip

Line 13: Setting the line style of the tail movieclip with a stroke height of 2 filled with green. For more information about drawing and line styles, check this tutorial.

Line 14: Placing the "pen" that will draw the tail on the same head _x and _y positions

Line 15: Defining the first node coordinates (nodes[0]) and the same head _x and _y positions. The first node actually could be the head itself, but I wanted a bigger head so I designed it as a separate movieclip.

Line 16: Beginning of the main loop, that will scan all nodes except nodes[0]. In this case, nodes[1] to nodes[99]

Line 17: Obtaining the angle between the xth and the (x-1)th node. This is done using trigonometry. I wrote a tutorial about it here. You may notice that is a bit different than the atan formulas used in that tutorial, but I discovered atan2 is often more useful than atan in applications involving rotation by a specified amount, because it returns a positive beta for all angles between 0 and 180 degrees (even when x is negative).
Thus it eliminates the need for extra code to deal with different values in different quadrants of the circle.

Lines 18-19: Here trigonometry is involved to calculate new node[x] x and y positions according to its angle with node[x-1]

Line 20: New x and y positions are saved in node[x]

Line 21: Drawing a line from the previous pen position to new x and y positions

And that's it! We have our moving string. Time to test for some collisions!

Collisions

I created a movieclip linked as wall and placed it on the stage.

Then the actionscript is:

ACTIONSCRIPT:
  1. tail_len = 2;
  2. tail_nodes = 100;
  3. nodes = new Array();
  4. _root.attachMovie("the_head", "the_head", 1, {_x:250, _y:200});
  5. _root.createEmptyMovieClip("the_tail", 2);
  6. _root.attachMovie("wall", "wall", 3, {_x:250, _y:200});
  7. for (x=1; x<tail_nodes; x++) {
  8.     nodes[x] = {x:the_head._x, y:the_head._y};
  9. }
  10. the_head.onEnterFrame = function() {
  11.     this._x = _root._xmouse;
  12.     this._y = _root._ymouse;
  13.     the_tail.clear();
  14.     the_tail.lineStyle(2, 0x00ff00);
  15.     the_tail.moveTo(the_head._x, the_head._y);
  16.     nodes[0] = {x:the_head._x, y:the_head._y};
  17.     for (var x = 1; x<tail_nodes-1; ++x) {
  18.         rotation = Math.atan2(nodes[x].y-nodes[x-1].y, nodes[x].x-nodes[x-1].x);
  19.         pos_x = nodes[x-1].x+tail_len*Math.cos(rotation);
  20.         pos_y = nodes[x-1].y+tail_len*Math.sin(rotation);
  21.         nodes[x] = {x:pos_x, y:pos_y};
  22.         if (wall.hitTest(pos_x, pos_y, true)) {
  23.             the_tail.lineStyle(2, 0xff0000);
  24.         }
  25.         the_tail.lineTo(pos_x, pos_y);
  26.     }
  27. };

Line 6: Placing the wall on stage

Line 22: Hit test between pos_x, pos_y coordinates and the wall

Line 23: If the test is positive, then change the line color to red. In this way you can view where you collided.

And now you're ready to create some string game... download the source code and send me your works!

Improve the blog rating this post
Tell me what do you think about this post. I'll write better and better entries.
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5 out of 5)
Loading ... Loading ...

» Flash Templates provided by Template Monster are pre-made web design products developed using Flash technology.
They can be easily customized to meet the unique requirements of your project.

33 Responses to “Creation of a game like String Avoider tutorial”

  1. Jerm on July 12th, 2007 4:53 pm

    Awesome!

  2. Mousey on July 12th, 2007 5:09 pm

    nice but what is the code so when it hits the wall it goes back to the begning position! And same for exit it goes to end

    thanks

  3. Flash Prayer on July 12th, 2007 8:12 pm

    heelo emanuele, i have posted a link to this tutorial at http://www.beedigital.net/blog I hope you don´t mind…

    Nice blog you have here, great tutorials….

    See you around.

  4. Michael on July 12th, 2007 8:15 pm

    Awesome, cannot believe how simple you make it seem, lol.

    To Mousey:
    Simply reset the head’s X and Y to wherever your start is inside the hitTest.

    if(wall.hitTest(pos_x, pos_y, true)){
    this._x = 250;
    this._y = 200;
    }

  5. abhilash on July 13th, 2007 11:36 am

    Cooool!!!

  6. eblup on July 14th, 2007 3:16 am

    good but what abount a second to youre platform game linke have enemys but good tut

  7. Samuel on July 17th, 2007 12:16 am

    I apologize, but in my mind this isn’t your best tutorial… I have no clue about how the string actually follows the mouse as it does, when the tail snail it’s way like it does. Could you post a part 2 that explains the calculations? :)

  8. And Mar on July 17th, 2007 2:16 pm

    Let me try to explain the trigonometry, Emanuele will correct me if I’m wrong:

    1.rotation = Math.atan2(nodes[x].y-nodes[x-1].y, nodes[x].x-nodes[x-1].x);

    Finds the angle(direction) between the current node and the previous

    node. This happens because the position of each node depends on the position of

    the previous node. This way, the nodes remain tail_len pixels apart.
    _
    nodes[x-1]->(_)
    \
    \
    \ (_)

    ———————————————————————–
    _
    (_)_____
    \ |
    \ |

  9. And Mar on July 17th, 2007 6:56 pm

    Man, my comment was cut if half.
    Let me try again.

  10. And Mar on July 17th, 2007 7:55 pm

    Let me try to explain the trigonometry, Emanuele will correct me if I’m wrong:

    1.rotation = Math.atan2(nodes[x].y-nodes[x-1].y, nodes[x].x-nodes[x-1].x);

    Finds the angle(direction) between the current node and the previous
    node. This happens because the position of each node depends on the position of

    the previous node. This way, the nodes remain tail_len pixels apart.
                                _
                   nodes[x-1]->(_)
                                 \
                                  \
                                   \ <— angle of this line from the
                                    \     horizontal is calculated
                                     \
                                      \_
                          nodes[x]—>(_)

    ———————————————————————–
                                _
                               (_)_____
                                 \     |
                                  \    | <– distance equals tail_len
                                   \   |
                                    \__|
    nodes[x] will be moved here ____/\
    so that the distance remains      \_
    tail_len                          (_)

    =======================================================================

    2.pos_x = nodes[x-1].x tail_len*Math.cos(rotation);

    Calculates the x position of the current node after it has been moved.

                 ___length of this line equals
              _  | _tail_len * Math.sin(rotation)
             (_)__(_)
               \   |\
                \  | currently, the node would be moved
                 \ | here
                  \|
                   \
                    \

    =======================================================================

    3.pos_y = nodes[x-1].y tail_len*Math.sin(rotation);

    Calculates the y position of the current node after it has been moved.

             _
            (_)___
              \   |
               \  |<— length of this line equals
                \ |     tail_len * Math.cos(rotation)
                 \|
                 (_) <— this is where the node finally ends up
                   \
                     <— As you can see, the node just
                          moves straight towards the previous node

    =======================================================================

    4.nodes[x] = {x:pos_x, y:pos_y};

    Updates the nodes[x] coordinates

    =======================================================================

    5.the_tail.lineTo(pos_x, pos_y);

    Draws a line (tail_len long) from current pen position

    (nodes[x-1].x,nodes[x-1].y), to the current nodes position
    (nodes[x].x,nodes[x].y or pos_x,pos_y)

    =======================================================================

    Hope this helps you out. Why the sin and cos statements work are
    explained in the tutorial Emanuele mentioned

  11. imworlds on July 19th, 2007 12:44 am

    Do these files work in Flash MX? I can’t get any of these to work. If not, is there a quick fix to make them work in Flash MX? I’d love to try these out…

  12. s0daplayer on July 19th, 2007 11:19 pm

    I’ve been looking how to make a game like this. Thanks.

  13. s0daplayer on July 20th, 2007 2:32 am

    I noticed that actually there will be one less node than defined. What is causing this.

  14. s0daplayer on July 20th, 2007 2:38 am

    Ok sorry for posting this question since it’s explained already. But if you want the same amount of nodes you defined, in line 16, remove the “-1″

  15. s0daplayer on August 6th, 2007 7:27 pm

    I created a game where the nodes would actually go where the node in front of it in the last frame. Though I’m wordering how to convert it so it will be like the nodes in this tutorial instead of manually making each mode.

    _root.attachMovie(”node”,”node1″,1,{_x:20, _y:100})
    _root.attachMovie(”node”,”node2″,2,{_x:275, _y:200})
    _root.attachMovie(”node”,”node3″,3,{_x:375, _y:300})
    _root.createEmptyMovieClip(”line1″,4)
    _root.createEmptyMovieClip(”line2″,5)
    _root.createEmptyMovieClip(”line3″,6)
    Mouse.hide()
    onEnterFrame = function() {
    node1._x = _xmouse
    node1._y = _ymouse
    node2._x = pos_x1
    node2._y = pos_y1
    node3._x = pos_x2
    node3._y = pos_y2
    line1.clear()
    line2.clear()
    line1.lineStyle(10, 0xabcdef)
    line2.lineStyle(10, 0xabcdef)
    line1.moveTo(node1._x,node1._y)
    line2.moveTo(node2._x,node2._y)
    line1.lineTo(node2._x,node2._y)
    line2.lineTo(node3._x,node3._y)
    pos_x1 = node1._x
    pos_y1 = node1._y
    pos_x2 = node2._x
    pos_y2 = node2._y
    }

  16. web design on August 19th, 2007 7:14 pm

    I tried in the first time as u said in the turorial…but seems somewhere i m not doing the correct coding or misspelled something ….anyways..nice tutorial..!!

  17. beatalize on September 20th, 2007 12:54 pm

    it doesnt work!!
    when i apply the first script it doesnt work y?

  18. 123 on September 20th, 2007 1:08 pm

    wow this tuturial is nice!!!

    guyz can anyone tell me how can i make the tail become red when the head touch my own tail?

  19. fwe on September 27th, 2007 9:43 pm

    I made String Avoider :D
    Nice tutorial

  20. Flávio on October 22nd, 2007 3:11 pm

    Hi! I liked this tutorial very much - as like all the rest of your tutorials…
    Anyway, I’ve been trying to make something similar to the string you made here, but waht I want was not a string, but a text following the mouse, and then I found this:
    http://www.a-to-s.co.uk/home.php
    click on N and you’ll see… would you please help me? I need this for a graduation project =)
    thanks in advance
    Flavio

  21. konishama on November 18th, 2007 11:21 am

    what action script is this?

  22. kam on November 21st, 2007 1:20 am

    Hi Guys, i have this working, i have a timer also set, but everytime i get the game to move to a diff “scene” in Flash the sting allways appears to start from the centre, i have only added a “gotoandplay” function and this just carrys on the action script for the string creation..can you please help me with how to stop this script from being carried over to the other “scene’s” in flash
    thank you

  23. bob mcshamusBdiddely on November 24th, 2007 6:12 pm

    to make the line follow the mouse without the head, just make the colour of the heads alpha 0%. This will make it invisible

  24. Goinginsane on December 5th, 2007 9:17 pm

    Could anyone post something for color codes?
    I can make the tail black, otherwise it is a hit and miss situation.

  25. blahblah on December 28th, 2007 10:48 pm

    i need a action script to make the wall move
    —————–
    blahblah

  26. josh on January 27th, 2008 10:04 pm

    i am willing to help, i am sorry if i am too late, but what do you want to happen exactly?

  27. Nathan on March 22nd, 2008 11:47 pm

    I’m making a game with this code
    http://dev.mrnat.com/bomb_sorter.swf
    It’s not done yet, but do you want me to credit you?

  28. Emanuele Feronato on March 23rd, 2008 1:03 am

    it would be very kind…

  29. Nathan on March 29th, 2008 12:33 am

    Are you sure I can use it?

    I really don’t like copying other people’s work…

  30. reece on June 5th, 2008 8:02 pm

    hey how do you keep the wall not moving with the mouse but so it stays in one place

  31. Eekie on June 12th, 2008 11:35 pm

    Does anyone know the code to make the tail (last node of the string) stationary (fixed) at a certain x,y coordinate? I want the string to follow the head but be limited to the tail_len… I am also trying to have the head drag rather than follow the mouse.

    Is this possible?

    Thanks!

    PS: Great tutorial…

  32. alex on August 17th, 2008 10:19 pm

    hey I put it all in and got a problem with the actionscript for the wall this is what it says

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 1: Statement must appear within on/onClipEvent handler
    tail_len = 2;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 2: Statement must appear within on/onClipEvent handler
    tail_nodes = 100;

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 3: Statement must appear within on/onClipEvent handler
    nodes = new Array();

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 4: Statement must appear within on/onClipEvent handler
    _root.attachMovie(”the_head”, “the_head”, 1, {_x:250, _y:200});

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 5: Statement must appear within on/onClipEvent handler
    _root.createEmptyMovieClip(”the_tail”, 2);

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 6: Statement must appear within on/onClipEvent handler
    _root.attachMovie(”wall”, “wall”, 3, {_x:250, _y:200});

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 7: Statement must appear within on/onClipEvent handler
    for (x=1; x<tail_nodes; x++) {

    Scene=Scene 1, Layer=Layer 1, Frame=1: Line 10: Statement must appear within on/onClipEvent handler
    the_head.onEnterFrame = function() {

    please email me the answer

  33. Robin on September 19th, 2008 1:51 pm

    Does someone know how to convert this code to AS3?? I’m struggling with it for the whole week now but can’t get a clue out of it! please help!

Leave a Reply