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:

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

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

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

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

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

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

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

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.

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (19 votes, average: 4.37 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.
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 59 comments

  1. Create a flash draw game like Line Rider or others - part 1 at Emanuele Feronato

    on February 3, 2007 at 5:20 pm

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

  2. ksb

    on February 4, 2007 at 5:40 am

    I want more already

  3. Izy

    on February 4, 2007 at 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.

  4. abhilash

    on February 4, 2007 at 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!!!

  5. mousey

    on February 4, 2007 at 10:52 pm

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

  6. And Mar

    on February 6, 2007 at 5:18 am

    really awesome!

  7. Videoking

    on February 9, 2007 at 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???

  8. Videoking

    on February 9, 2007 at 3:35 am

    sorry my website was http://www.freewebs.com/videoking000

  9. Sebastian

    on February 14, 2007 at 1:27 pm

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

  10. Joachim

    on February 15, 2007 at 7:31 pm

    WOw! Great flash tuts.. :D

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

    ;)

  11. Create a flash draw game like Line Rider or others - part 3 at Emanuele Feronato

    on February 17, 2007 at 5:54 pm

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

  12. miffy

    on February 17, 2007 at 5:57 pm

    cool

  13. V34

    on February 17, 2007 at 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!

  14. Josh

    on February 19, 2007 at 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?

  15. blake

    on February 20, 2007 at 7:30 pm

    help me there is an error in the code

  16. I Need Help

    on February 21, 2007 at 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

  17. xeronar

    on February 22, 2007 at 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.

  18. Create a flash draw game like Line Rider or others - part 4 at Emanuele Feronato

    on March 5, 2007 at 10:48 am

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

  19. I need help too

    on March 16, 2007 at 4:14 am

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

    please help us!

  20. Anders

    on March 18, 2007 at 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 ;)

  21. alcho

    on March 28, 2007 at 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?

  22. Bennyhaha2

    on March 30, 2007 at 4:30 pm

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

  23. M&M

    on March 31, 2007 at 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!

  24. And Mar

    on March 31, 2007 at 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!

  25. silentfire

    on April 26, 2007 at 8:27 pm

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

  26. silentfire

    on April 26, 2007 at 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

  27. Jefix

    on April 30, 2007 at 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?

  28. the new dude XD

    on May 5, 2007 at 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)

  29. the new dude XD

    on May 5, 2007 at 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

  30. Matt

    on May 5, 2007 at 5:30 pm

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

  31. Matt

    on May 5, 2007 at 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

  32. bob

    on May 12, 2007 at 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!!)

  33. general_zim

    on June 20, 2007 at 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

  34. stick pics

    on June 22, 2007 at 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!

  35. chris

    on June 22, 2007 at 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??

  36. Jax

    on July 20, 2007 at 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…

  37. hazz

    on July 26, 2007 at 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 !!!!!!!!!

  38. Chefi-

    on October 12, 2007 at 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?

  39. torskmunken

    on October 19, 2007 at 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.

  40. trainee

    on November 23, 2007 at 2:00 am

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

  41. Riccardo

    on December 31, 2007 at 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!!

  42. josh

    on January 12, 2008 at 8:32 am

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

  43. Chris Leeman

    on February 20, 2008 at 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).

  44. Umer

    on February 22, 2008 at 6:49 pm

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

  45. trainee

    on February 23, 2008 at 4:25 pm

    so wheer do i put the codes????

  46. Gamitude

    on February 26, 2008 at 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

  47. Søren Houen

    on March 6, 2008 at 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

  48. Prototype of a Flash game like Floaty Light : Emanuele Feronato - italian geek and PROgrammer

    on May 7, 2008 at 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. [...]

  49. stevie

    on May 9, 2008 at 5:29 pm

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

  50. Create a Flash game like ColorFill - part 1 : Emanuele Feronato - italian geek and PROgrammer

    on June 23, 2008 at 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 [...]

  51. slym

    on July 24, 2008 at 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?

  52. fezziwig

    on July 28, 2008 at 10:06 pm

    does his tutorial work on flash 8

  53. AS3 Flash game creation tutorial - part 3: walls : Emanuele Feronato

    on November 6, 2008 at 4:30 pm

    [...] You can find the theory behind this method of collision in Create a flash draw game like Line Rider or others – part 2. [...]

  54. Harrison

    on November 10, 2008 at 7:03 pm

    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

  55. Anonomous

    on December 11, 2008 at 11:05 am

    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

  56. nick

    on June 24, 2009 at 7:34 pm

    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

  57. anonymous

    on October 11, 2009 at 10:46 pm

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

  58. rob

    on October 27, 2009 at 5:40 pm

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

    Just kidding. THANKS!!!

  59. Ethan

    on November 26, 2010 at 5:48 pm

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