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:

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

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

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

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.

  • Pingback: Create a flash draw game like Line Rider or others - part 1 at Emanuele Feronato()

  • ksb

    I want more already

  • Izy

    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.

  • abhilash

    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!!!

  • mousey

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

  • And Mar

    really awesome!

  • 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???

  • Sebastian

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

  • WOw! Great flash tuts.. :D

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

    ;)

  • Pingback: Create a flash draw game like Line Rider or others - part 3 at Emanuele Feronato()

  • miffy

    cool

  • V34

    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!

  • Josh

    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?

  • blake

    help me there is an error in the code

  • 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

  • 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.

  • Pingback: Create a flash draw game like Line Rider or others - part 4 at Emanuele Feronato()

  • I need help too

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

    please help us!

  • 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 ;)

  • alcho

    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?

  • Bennyhaha2

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

  • M&M

    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!

  • And Mar

    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!

  • silentfire

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

  • silentfire

    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

  • Jefix

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

  • 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)

  • 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

  • Matt

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

  • Matt

    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

  • bob

    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!!)

  • 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

  • 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!

  • chris

    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??

  • Jax

    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…

  • hazz

    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 !!!!!!!!!

  • Chefi-

    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?

  • torskmunken

    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.

  • trainee

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

  • Riccardo

    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!!

  • josh

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

  • 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).

  • Umer

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

  • trainee

    so wheer do i put the codes????

  • 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

  • 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

  • Pingback: Prototype of a Flash game like Floaty Light : Emanuele Feronato - italian geek and PROgrammer()

  • stevie

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

  • Pingback: Create a Flash game like ColorFill - part 1 : Emanuele Feronato - italian geek and PROgrammer()

  • 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?

  • fezziwig

    does his tutorial work on flash 8

  • Pingback: AS3 Flash game creation tutorial - part 3: walls : Emanuele Feronato()

  • Hey ok, big problem, when i create my blue ball i make it a symbal to movie clip but then when i put in the codeing on the very first code it doesnt fall down like the ball.. its wierd.. my ball doesnt seem to do anything with the coding. HELP

  • hi
    can i request a tutorial on how to make him roll up a slope because icont figure it out thanks ur a gun mate

    miutubevids

  • nick

    hi! i’ve been following the tutorials but now i’ve come over a problem. in the actionscript in the frame it says that the onClipEvent handler is only used for movieclip instances. any help here? were should i put this code

  • anonymous

    you don’t need to use trigonometry. Just use terrain.hitTest(ball)

  • rob

    hey, I don’t want a ball, I want a car!!

    Just kidding. THANKS!!!

  • Ethan

    I did the program actionscript exactly, but the ball won’t fall. Why is this???

  • ari

    This is great but can you help me

    What if I want the ball dropped when I click on the ball
    how should I make it? please let me know and I am very grateful

  • Someone

    Using y=y+yspeed will cause the collision bug. It is better to increment y by one yspeed times.