Create a flash draw game like Line Rider or others - part 2

March 31st update: part 5 released
March 4th update: part 4 released
February 17th update: part 3 released

In this part I'll explore how to detect collision between a ball and the line.

Please read part 1 if you didn't already.

You may say: "hey, I don't want a ball, I want a car!!". There's no problem, you will learn everyting, I will explain, during next tutorials, how to insert complex objects, but the basics are the same for every collision.

The easy way

Ok, let's imagine you have the purple line in the movie, and the blue ball you see.

The actionscript in the blue ball is:

ACTIONSCRIPT:
  1. onClipEvent (load) {
  2.     yspeed = 0;
  3.     xspeed = 0;
  4.     gravity = 0.2;
  5. }
  6. onClipEvent (enterFrame) {
  7.     if (_root.go == true) {
  8.         yspeed = yspeed+gravity;
  9.         if (_root.terrain.hitTest(_x, _y, true)) {
  10.             yspeed = 0;
  11.         }
  12.         _y = _y+yspeed;
  13.         _x = _x+xspeed;
  14.     }
  15. }

Lines 1-5: These instructions are execute only once, when the ball firstly appears on the stage. If you followed my flash game creation tutorial you are familiar with those instructions. I am defining ball x and y speed (set to 0, the ball does not move) and the gravity.

Lines 6-15: These are the instructions execute every time the ball is on the stage... every 1/50 seconds in our case.

On line 7 you may see that the whole cycle is executed only when a variable called "go" is true. Don't worry about it, I put this control to let the ball fall only when you click on the stage.

Line 8: gravity value is added to yspeed. You should easily understand these instructions, if not check flash game creation tutorial part 1 and all will be clear

Lines 9-11: The core of this script: I check the collision between the ball and the terrain, and if positive, I stop the ball. Stopping the ball is the first thing to do before bouncing.

Well, let's test the script now! It should work!

Hmmm... it didn't work as I expected... I want the ball to stop when it collides with the ground... but in this case the ball passed the ground as it crashed it.

What's wrong then? Let's see this instruction: _root.terrain.hitTest(_x, _y, true)... you can see the collision is checked on _x and _y ball values... the center of the ball. If you look at the movie, you may see the ball stopped once its center was in collision with the ground.

The hardest way

The solution now is: don't worry about the center and let's check the collision between the ground and the ball circumference

Let's try this actionscript, then

ACTIONSCRIPT:
  1. onClipEvent (load) {
  2.     yspeed = 0;
  3.     xspeed = 0;
  4.     gravity = 0.2;
  5.     radius = 25;
  6.     precision = 90;
  7. }
  8. onClipEvent (enterFrame) {
  9.     if (_root.go == true) {
  10.         yspeed = yspeed+gravity;
  11.         for (x=1; x<precision; x++) {
  12.             spot_x = _x+radius*Math.sin(x*360/precision);
  13.             spot_y = _y-radius*Math.cos(x*360/precision);
  14.             if (_root.terrain.hitTest(spot_x, spot_y, true)) {
  15.                 yspeed = 0;
  16.             }
  17.         }
  18.         _y = _y+yspeed;
  19.         _x = _x+xspeed;
  20.     }
  21. }

Line 5: A new variable is initialized, the radius variable. It contains the value of the radius of our ball, in pixels

Line 6: Another new variable, called precision. We'll see how the higher the precision, the more accurate the collision checking, the more CPU expensive the game. It's up to you finding the right compromise between accuracy and CPU.

Line 11: A cicle executed precision times

Lines 12-13: spot_x and spot_y are the coordinates of points at ball's circumference taken every 360/precision degrees. And on line 14 you can see I am checking the collision between these points (the circumference) and the terrain.

Let's see if does it work.

It works!! The ball stops on the ground without passing it!!

Two things:

1) Since this operation could be CPU expensive, remember to find a compromise between precision and performances. In most cases, the smaller the ball, the less precision needed.

2) Always try so set precision as a number that perfectly divides 360. I mean values like 36,45,72,90,180. I found 90 is a good value in most cases.

Yeah, I solved the problem, congratulations and so on...

Getting harder and harder... how many collisions?

It's not as easy as it seems...

Look at this actionscript

ACTIONSCRIPT:
  1. onClipEvent (load) {
  2.     yspeed = 0;
  3.     xspeed = 0;
  4.     gravity = 0.2;
  5.     radius = 25;
  6.     precision = 90;
  7. }
  8. onClipEvent (enterFrame) {
  9.     if (_root.go == true) {
  10.         collisions = 0;
  11.         yspeed = yspeed+gravity;
  12.         for (x=1; x<precision; x++) {
  13.             spot_x = _x+radius*Math.sin(x*360/precision);
  14.             spot_y = _y-radius*Math.cos(x*360/precision);
  15.             if (_root.terrain.hitTest(spot_x, spot_y, true)) {
  16.                 yspeed = 0;
  17.                 collisions ++;
  18.             }
  19.         }
  20.         _root.collisions.text = collisions + " collisions detected";
  21.         _y = _y+yspeed;
  22.         _x = _x+xspeed;
  23.     }
  24. }

Basically it's the same script with three more instructions:

Line 10: A collisions variable is set to zero.

Line 17: Everytime a collision is checked, the collisions variable is incremented

Line 20: I show the collision value. You may thing this value will be 1...

Test the script...

I got an "8"... meaning that what seems a single collision, in reality is made of eight collisions. If you raise the precision to 360, you should get something around 27. I mean twentiseven different collisions, and only one to choose.

What can I do?

Collisions - the final word

Check this last (at the moment) actionscript

ACTIONSCRIPT:
  1. onClipEvent (load) {
  2.     yspeed = 0;
  3.     xspeed = 0;
  4.     gravity = 0.2;
  5.     radius = 25;
  6.     precision = 360;
  7. }
  8. onClipEvent (enterFrame) {
  9.     if (_root.go == true) {
  10.         collisions = 0;
  11.         sum_x = 0;
  12.         sum_y = 0;
  13.         yspeed = yspeed+gravity;
  14.         for (x=1; x<precision; x++) {
  15.             spot_x = _x+radius*Math.sin(x*360/precision);
  16.             spot_y = _y-radius*Math.cos(x*360/precision);
  17.             if (_root.terrain.hitTest(spot_x, spot_y, true)) {
  18.                 yspeed = 0;
  19.                 collisions++;
  20.                 sum_x += spot_x;
  21.                 sum_y += spot_y;
  22.             }
  23.         }
  24.         if (collisions>0) {
  25.             spot_x = sum_x/collisions;
  26.             spot_y = sum_y/collisions;
  27.             createEmptyMovieClip("lines", 100000);
  28.             lines.lineStyle(3, 0x000000, 100);
  29.             lines.moveTo(0, 0);
  30.             lines.lineTo(spot_x-_x, spot_y-_y);
  31.         }
  32.         _y = _y+yspeed;
  33.         _x = _x+xspeed;
  34.     }
  35. }

Lines 11 and 12: I declare two new variables, sum_x and sum_y and set them to zero.

Lines 20 and 21: If a collision is checked, I add to sum_x the value of spot_x (the x value of circumference collision) and to sum_y the value of spot_y (same thing for the y value).

Line 24: Check if collisions is greater than zero, in this case...

Lines 25-26: the new spot_x, the (almost) real point where the ball collided with the ground, is determined dividing the sum_x variable by the number of collisions. In other words, I am finding the average point of all collisions occurred. Same thing with the spot_y

Lines 27-30: I am just showing a movieclip with a line that goes from the center of the ball to the spot with the average collisions detected

Look at the movie.

This time it works for real.

That's all at the moment, download the full sources of all examples and give me feedback, in next lesson I will explain how to make the ball bounce.

Have fun.

Related Item: casino game

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 (4 votes, average: 3.75 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.

52 Responses to “Create a flash draw game like Line Rider or others - part 2”

  1. ksb on February 4th, 2007 5:40 am

    I want more already

  2. Izy on February 4th, 2007 5:55 am

    This is wonderful. Your tutorials are the best.

    Just before I read your tutorial today, I thought of a way to determine the angle of the line that the sled or whatever is hitting by using two separate objects, one at the front and one at the back.

    Each would be pulled down by gravity, and each one has its own hitTest, and the angle could be determined by the different elevations at which they come to rest on the line. The sled is then suspended in the center of the two objects and rotated at the appropriate angle.

    But yours more concise, if more processor intensive. I don’t think I ever would’ve quite figured out everything in your approach.

    Can’t wait for the next installment.

  3. abhilash on February 4th, 2007 8:54 am

    this was a cool tutorial. can I submit a game which I have made on my own(not following ur tutorials)
    last thing
    this is the place for learning flash for a 13 year old kid!!!

  4. mousey on February 4th, 2007 10:52 pm

    Hey, this is great ! keep it up i hope the next tutorial will be soon.

  5. And Mar on February 6th, 2007 5:18 am

    really awesome!

  6. Videoking on February 9th, 2007 3:34 am

    hey abhilash,

    Are you relaly 13 bacause i am really 11!! I’ve been trying to figure stuff out and tutorilized.com is a great polace to learn flash!! I can’t wait for the gravity part!! Dose anyone know when it’s going ot be finishes??

    http://www.freewebs.com/videoking0000 abhilash, this is my weebsite i completely made with falsh i have a couple games and things n-but not that cool! Do u have a website???

  7. Videoking on February 9th, 2007 3:35 am
  8. Sebastian on February 14th, 2007 1:27 pm

    What about the “hitTest()” feature in Flash? Why don’t you use this, it would be much more easier.

  9. Joachim on February 15th, 2007 7:31 pm

    WOw! Great flash tuts.. :D

    Sebastian: he is using hitTest()
    _root.terrain.hitTest(spot_x, spot_y, true)

    ;)

  10. miffy on February 17th, 2007 5:57 pm

    cool

  11. V34 on February 17th, 2007 6:02 pm

    I replaced the:
    radius = 25;

    With:
    radius = Math.floor(this._width/2);

    This way it find the radius itself.
    Thanks Emanuele Feronato, for your great tutorials!

  12. Josh on February 19th, 2007 5:35 am

    All of your tutorials are AMAZING, they are definately the best ones i’ve seen. However I have one question and im not sure if it will be answered in your next tutorial.
    My question is: how would I go about making the ball roll on the line drawing from the first tutorial?

  13. blake on February 20th, 2007 7:30 pm

    help me there is an error in the code

  14. I Need Help on February 21st, 2007 11:45 pm

    i dont get this at all i added the code and it says error so when i select the ball i drew it works but when i click on the ball it doesnt move att all do i have to start out with lines im confused

  15. xeronar on February 22nd, 2007 4:03 pm

    i have the same problem… the ball doesn’t move at all, even when you click it… I think this has something to do with the: if (_root.go == true) code… there does’t seem to be a way of making go = true, so the ball will not move, can you please correct your code.

    p.s. my website is: http://www.xeronar.co.uk.tt check it out… im hoping to have the game up and running very soon.

  16. I need help too on March 16th, 2007 4:14 am

    i have the same problem as “xeronar” and “I Need Help”.

    please help us!

  17. Anders on March 18th, 2007 2:41 pm

    I can’t make it work =/

    Email me if you can help me: anders . s . moen (at) gmail . com
    (Just take the spaces away which you probably could think yourself ;)

  18. alcho on March 28th, 2007 12:13 pm

    Hmm, i have been looking at this code to try and fix a problem i am having.

    What if the ball was falling so fast (say the yspeed got all the way to 30) and then started to fall through the lines (missing the hittest).Because the image could move down by 30 and the line width may only be 25.

    Any solutions?

  19. Bennyhaha2 on March 30th, 2007 4:30 pm

    I cant get the ball to drop plz email me if any solutions
    bfennellster@gmail.com

  20. M&M on March 31st, 2007 8:40 am

    Please Help!

    I’ve Got The Same Problem As I Need Help, Xeronar & I Need Help Too!

    I Can’t Get The Ball To Fall! :(
    Please Help!
    Is it the code? or something i have done?

    HELP!

  21. And Mar on March 31st, 2007 9:52 pm

    This is for people who cant make the ball fall.

    Go to the actions screen for the go button and enter this code:

    on(release){
    _root.go = true;
    }

    That should work!

  22. silentfire on April 26th, 2007 8:27 pm

    it is saying that the yspeed and xspeed pur creating a syntax error in lines 2 and 3 of the ball

  23. silentfire on April 26th, 2007 8:37 pm

    never mind sry bout that it was jsut in he wrong place… but now i cant get the ball to fall when i test the movie

  24. Jefix on April 30th, 2007 6:20 pm

    hi, i can let the ball fall but when it gets on the line it goes into the line can anyone help me plz?

  25. the new dude XD on May 5th, 2007 4:10 pm

    dude i have seen part one and i have a actionscriptfile but you sent me an other one do i have to delete the first one?

    if i dont where i need to put the new sript?
    pleas help me out im not that pro in flash so say it easy

    (srry for my englisch)

  26. the new dude XD on May 5th, 2007 4:21 pm

    man i need realy fast help ‘
    i dont know where to put the sript? XD
    i know n00bie.
    do i need to keep the first part sript yes or no plz tel me fast

  27. Matt on May 5th, 2007 5:30 pm

    When i go to test the movie the ball wont drop what is wrong

  28. Matt on May 5th, 2007 5:35 pm

    another problem for me i used the new code that someone gave but when im in test movie or scene i go to click the ball to let it drop and i get the little hand that would make it click but i click on the ball and nothing happens i have also had this same problem trying to create buttons for games is the actionscript wrong plz help

  29. bob on May 12th, 2007 12:17 am

    I’m sure that cos must be swapped with sin. This doesn’t actually solve any problems but it makes it more accurate (and it is right!! just look at how right I am!!)

  30. general_zim on June 20th, 2007 3:49 am

    Hi! This tutorial was great, and I wanna do something exactly like this.

    But, I wanna make a rollercoaster themed game. Is there anyway where you can have the player draw the track, then the rollercoaster car is attacthed to the track, so it doesn’t go off the track?

    Please reply via email if anyone (or the author) knows how to accomplish something of this nature.

    -general_zim

  31. stick pics on June 22nd, 2007 10:54 am

    hiya, great tutorial - very clear…

    on part one you said you would demonstrate how to save the picture…

    “In the next step I’ll teach you how to save the drawing “…

    I can’t seem to find where you have done this? The reason I ask is because I have implemented a flash drawing (albeit very primitive) on the website above (http://www.shitstickpics.com/draw.php) and I am wanting to save the drawing that users make as an image …

    do you know how this can be done? Thanks!

  32. chris on June 22nd, 2007 5:30 pm

    when i do it the ball dont move, i tried drawing it and converting it into a movieclip, button and graphic but nothing has happend, i typed the action script in nothing still happend why??

  33. Jax on July 20th, 2007 12:37 pm

    I have the same problem as alcho, only the speed doesn’t seem to affect it.
    I mucked around with the radius, but it didn’t seem to make much difference…

  34. hazz on July 26th, 2007 9:23 pm

    ive read it throught 20 times i did the first tut perfect so i drew a line i made a ball converted it 2 movi clip then pasted the first code in the actions pannel the tested the movie !!!!it dident move !!!!!!!!!

  35. Chefi- on October 12th, 2007 10:30 pm

    So I have also this problem that if the speed is like over 1 it will let the ball littlebit inside the obstacle if speed is like 30 it may almost go throught it.

    I did try to tweak precision but it didint help anything.

    Nice tutorial but im rly despered with this problem. Any 1 solved this problem?

  36. torskmunken on October 19th, 2007 10:45 pm

    hello. you should also explain the shapeflasg thing in the hittest. its prerty useful in these kind of games i saw today, when i tryed to fix a problem. now i know what it means, i think. youre the god of programmers.

  37. trainee on November 23rd, 2007 2:00 am

    hey how do i make it play do i put it in note pad or sumthing?

  38. Riccardo on December 31st, 2007 3:52 pm

    Fantastic!!!!!
    i used to check collisions at fixed points on a ball ( the corners(4) the top, the bottom, left and right).

    Never thought about calculating collisions on the whole circumfernce.
    Thank you a lot for these tutorials!!

  39. josh on January 12th, 2008 8:32 am

    i did the first script on this page and when i tested it out, the ball didn’t fall.

  40. Chris Leeman on February 20th, 2008 9:36 pm

    This is a good example of collision detection, but you should not use clip events (they’re deprecated). Instead your code should go in the first frame of the timeline.

    get rid of:
    onClipEvent (load)
    onClipEvent (onEnterFrame)

    just put the variable declarations at the top of the actionscript in the frame. For the onEnterFrame event, use:
    ball.onEnterFrame = function() {}

    also be sure to reference ‘ball._x’ instead of ‘_x’, etc…

    Not to knock the script because I really do like it, but when I change the angle of the terrain line, the ball sometimes lands far away from the line (even with increased precision).

  41. Umer on February 22nd, 2008 6:49 pm

    I don’t get the math function i wish if there were diagram showing circle and cos sin things
    you konw

  42. trainee on February 23rd, 2008 4:25 pm

    so wheer do i put the codes????

  43. Gamitude on February 26th, 2008 11:44 pm

    Great tutorial. Still hoping to find some more efficient ways to find out the contact point in the collision apart simply trying every place in the circle. Because that would require too much processing with lots of balls.

    @umer, and the rest confused about cos and sin:
    Depending on where you start making your way through the circle(t=0) you can use either cos or sin… for example you could also use x=r*cos t and y=r*sin t, and you’ll get the same result. For more info:
    http://en.wikipedia.org/wiki/Trigonometry

  44. Søren Houen on March 6th, 2008 3:10 am

    Hi Emanuele

    This site is great! Your tutorials are amazing man. Just a small performance tweak for this one, though
    In these lines:

    for(…) {
    spot_x = _x+radius*Math.sin(x*360/precision);
    spot_y = _y-radius*Math.cos(x*360/precision);
    }

    you are doing two unnecessary divisions per for loop which could be replaced with a

    var precision_360 = 360/precision;

    statement above the for loop, followed by
    for(…)
    spot_x = _x+radius*Math.sin(x*precision_360);
    etc….

    That’ll save you two division per for loop

  45. stevie on May 9th, 2008 5:29 pm

    hey emmanuell every time i ask u something u ignore me. plz! write back to me!

  46. slym on July 24th, 2008 7:57 pm

    I want to make it so that in the area that you can draw there are lines already there. That way its like a challenge to get to the finish. Can anyone help me?

  47. fezziwig on July 28th, 2008 10:06 pm

    does his tutorial work on flash 8

Leave a Reply




Trackbacks

  1. Create a flash draw game like Line Rider or others - part 1 at Emanuele Feronato on February 3rd, 2007 5:20 pm

    [...] February 3rd update: part 2 released [...]

  2. Create a flash draw game like Line Rider or others - part 3 at Emanuele Feronato on February 17th, 2007 5:54 pm

    [...] Read lessons 1 and 2 if you haven’t done it already. [...]

  3. Create a flash draw game like Line Rider or others - part 4 at Emanuele Feronato on March 5th, 2007 10:48 am

    [...] Here we go with the 4th part. Read steps 1, 2 and 3 and you’re ready to go. [...]

  4. Prototype of a Flash game like Floaty Light : Emanuele Feronato - italian geek and PROgrammer on May 7th, 2008 7:46 pm

    [...] in the Flash game creation tutorial - part 1 post, the collision detection as shown in the Create a flash draw game like Line Rider or others - part 2 post and the control system already seen at A new player control concept, with only a minor change. [...]

  5. Create a Flash game like ColorFill - part 1 : Emanuele Feronato - italian geek and PROgrammer on June 23rd, 2008 4:32 pm

    [...] previous concepts from Create a flash draw game like Line Rider or others - part 2 are involved in order to determine collisions between the ball and the line. PLAIN TEXT [...]