Best viewed in Firefox

Awesty Productions

Efficient Collision Detection with Dynamically Created MC’s

May 11th, 2007 by awesty

In this tutorial we will check for collisions between MC’s (Movie Clips) that are created through actionscript. The way we will be doing it won’t lag very much compared to a lot of the other ways you can do this and I will explain why later. I am using Adobe Flash CS3 but Macromedia Flash 8 and Flash MX 2004 will work as well. If you are using Flash CS3 make sure you select a AS 2.0 file.

Click here to see an example of what we will be making.

Open a new flash document and make a bullet or something, make this a MC. This is the MC that is going to be attached to the stage through action script. Make another MC which can be a wall or something you want the bullets to hit. (Make the bullet facing upwards and make the wall horizontal).

Making the Movie Clips

Since we will be attaching the bullets through actionscript delete the one you just made of the stage. Put the wall up close to the top of the stage since we will be putting the bullets down the bottom. Open the library (Ctrl+L or Windows>Library) and right click on the bullet MC. Select ‘Linkage…’. A new window should appear.

Linking the MC1

Make sure the box reading ‘Export for Actionscript’ is checked. Enter ‘bullet’ into the identifier box. Here is what it should look like. (The Flash CS3 Linkage box looks different to the Flash 8 one so I put an example for each).

Flash CS3
Linking the MC2

Flash 8
Linking the MC2

Give the wall an instance name of ‘wall’.

Now paste this script onto the frame.

var bullets:Array = new Array();
var i:Number = 0;

onEnterFrame = function () {
    if (random(10) == 0) {
        attachMovie("bullet","b"+i,getNextHighestDepth(),{_x:random(Stage.width), _y:Stage.height});
        bullets[bullets.length] = i;
        i++;
    }
    for (j=0; j<bullets.length; j++) {
        n = bullets[j];
        _root["b"+n]._y -= 20;
        if (_root["b"+n].hitTest(_root.wall)) {
            removeMovieClip(_root["b"+n]);
            bullets.splice(j,1);
        }
    }
};

The first two lines are declaring two variables. The first one is an array called bullets. This is where all the bullets are being stored when they are created. There other is a number called i, which increases everytime a bullet is created.

‘onEnterFrame’ tells flash to run the code between the curly braces every time the frame is entered.

if (random(10) == 0) {
        attachMovie("bullet","b"+i,getNextHighestDepth(),{_x:random(Stage.width), _y:Stage.height});
        bullets[bullets.length] = i;
        i++;
    }

This is an if statement that checks if a random number between 0 and 9 is equal to 0. If it is it will attach the MC ‘bullet’ to the stage with an instance name of ‘b’+i. So if i is equal to 0 its instance name will be b0, if i is 12 than its instance name will be b12. It is setting its _x coordinates to a random number from 0 to the stage width (so its _x could be anywhere on the stage) and its setting its _y coordinates to the stage height.
It is adding the value of i to the end of the bullets array. bullets.length equals how many numbers are in the bullets array. After it does all that i increases by one so that none of the bullets have the same name.

for (j=0; j<bullets.length; j++) {
        n = bullets[j];
        _root["b"+n]._y -= 20;
        if (_root["b"+n].hitTest(_root.wall)) {
            removeMovieClip(_root["b"+n]);
            bullets.splice(j,1);
        }
    }

This is what makes our script run faster. The most common way is ‘for(j=0;j<i;j++)’. So if 165 bullets had been created this script would run 165 times. But since not all of the bullets are going to be on the stage (they get deleted when they hit the wall) this is making flash run the script more than it has to. Since this code only runs of j is less than b bullets.length, and when a bullet gets deleted so does its number in the array, flash only runs the code as many times as it needs to. Sorry if I didn’t explain that very well. If you still need me to explain it better just post below.
The 2nd line is making a variable called n equal to bullets[j]. If j is equal to 12, and the 12 value in the bullets array is equal to 34 then n is going to equal 34. This just saves us from writing bullets[j] over and over and lets use put ‘n’ instead.
The next line is telling each bullet on the stages _y to decrease by 20, so it moves up. If n is equal to 54 than _root[”b”+n] means _root.b54.

if (_root["b"+n].hitTest(_root.wall)) {
            removeMovieClip(_root["b"+n]);
            bullets.splice(j,1);
        }

This checks if any of the bullets are hitting the wall. If they are they are removed with the removeMovieClip function. The second last line is removing that bullet from the bullets array so that flash doesn’t run the script for that bullet anymore. We are using the splice function to do this. The first parameter is the value you want flash to start deleting from. The next parameter is how many values after that you want to delete. So if you put 12 flash would delete 12 values from your array, starting from the value you put.

I hope I explained that code well enough. If I didn’t just post the part you didn’t understand underneath. If you test your movie (Ctrl+Enter) you should see something like this.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • del.icio.us
  • digg
  • Furl
  • MyShare
  • NewsVine
  • Netscape
  • Reddit
  • Simpy
  • Slashdot
  • StumbleUpon
  • Technorati
  • YahooMyWeb

RSS feed | Trackback URI

58 Comments »

Comment by Kurt Subscribed to comments via email
2007-05-12 22:08:28

Nice I’m first for once good tutorial

 
Comment by randall Subscribed to comments via email
2007-05-13 14:20:01

How do you make a button that will brong you to any frame or scene you want it to? (im making a gallery of all my movies so I want to make a frame with a bunch of buttons leading to each clip)

 
 
Comment by randall Subscribed to comments via email
2007-05-13 14:24:26

srry but if you are online i need to know really badly, cuz im supposed to be done tonite, oh and my email isnt working right now I need you to send a comment on this site :)

Comment by awesty
2007-05-14 17:16:48

on(release){
gotoAndPlay(FrameNumber, “SceneName”);
}

 
 
Comment by randall Subscribed to comments via email
2007-05-13 14:31:08

:(

Comment by GM Subscribed to comments via email
2008-06-27 15:06:09

on(release){
gotoAndStop(“SceneName”, FrameNumber)
}

 
 
Comment by Kurt Subscribed to comments via email
2007-05-13 21:50:02

Well randall i don’t really do scene but i know how to bring you to a frame

on the button put:

on(release){
gotoAndStop(THE FRAME NUMBER);
}

on(release){ =

when your left mouse button was clicked then on the release of it

gotoAndStop(THE FRAME NUMBER);
}

= go to and stop on frame The number just change that to the frame number.

Comment by Kurt Subscribed to comments via email
2007-05-13 21:51:41

IT CAN NOT BE A COMPONENT BUTTON!

 
 
Comment by Bitwize Subscribed to comments via email
2007-05-15 18:35:29

Hey dude,

I have a walk cycle

up,down,left,right,standing bored etc

when you tap buttons it plays fine

but buttons held down make the play loops stay on frame 1 of the walk cycles not giving them a chance to play throught even once… whats the most logical way to make them play a walking cycle once BUT if held down it cycles through the whole thing?

(this is not a straight down view rotate style)

Comment by awesty
2007-07-02 18:31:05

Can you show me the current code?

 
 
Comment by Kurt Subscribed to comments via email
2007-05-17 08:37:34

Ok Awesty I am having a problem with a system I have made http://kfb-zone.com/flash/Kurt’s_system.swf

Well when ever you go to the log shop and exit the dynamic text restarts the exit button Actionscript is

on(release){
gotoAndStop(1);
}

can you please tell me how i would fix this (just to tell you this is my 1st rough draft there might be 5 or more rough drafts till i start adding graphics.)

Comment by Kurt Subscribed to comments via email
2007-05-17 08:40:17

That’s weird it is not working for me to the link i will change the name of the link to

http://kfb-zone.com/flash/Kurtssystem.swf

and now it is.

Comment by Kurt Subscribed to comments via email
2007-05-21 00:44:16

Hey Awesty I fixed it,

frame one had the code

stop();
_root.xp2 = 0;
_root.pack = 0;
_root.gold2 = 0;
_root.lvl = 1;
_root.xpuxp2 = 83;
_root.gold = 0;
_root.oaklog = 0;
if(_root.gold

 
 
 
Comment by Cecil Subscribed to comments via email
2007-05-18 23:12:20

I am having a problem with the tutorial. I did the linkage, I made the movie clips with instance name and I added your action script to the frame but nothing is happening. Does it matter what direction my bullets face or do I need to modify the action script to do that?

 
Comment by Cecil Subscribed to comments via email
2007-05-18 23:18:31

Never mind sorry for stupid comment I turned it around and it started working thanks for tutorial.
But how do I do it if I want to turn it around and make it go downwards not upwards? =/

Comment by awesty
2007-07-02 18:33:43

Well you need to attach them above the stage, instead of below and make there _y decrease instead of increase.

 
 
Comment by Kurt Subscribed to comments via email
2007-05-21 00:46:05

Ok not this again well I have to enter another message to view the message before.

Comment by Kurt Subscribed to comments via email
2007-05-21 00:50:31

Ok my solution didn’t work but i did fix it

I wont explain it anymore tho because it has the code and i don’t want people cheating when i use this for a game like when someone dose something like, ( im not doing the real code)

on release
root. something += something

send to http://kfb-zone.com/flash/Kurtssystem.swf

 
 
Comment by Calum Subscribed to comments via email
2007-05-30 06:24:18

Hi awesty,

I was wonderig if u could help me with my health br code for my game… what happens is, when it looses health and the health bar MC reduces in size, instead of reducing from right to left… it reduces from right and left and reduces into the middle. Why does it do that? every other game i added a health bar it worked. i went through your health tutorial 16 times. But still it doesn’t do it like in your tutorial.

Can you help?

If you need source code then just send me an email to calums1994@hotmail.co.uk if you need it , then ill attach it and send it back.

Thanks

Calum :)

Comment by awesty
2007-07-02 18:30:09

Just email me at
sniper_rifle_048[@]hotmail[.]com

 
 
Comment by Bitwize Subscribed to comments via email
2007-05-30 19:00:45

hey there,

I have a walk cycle in a RPG game and it plays through them fine if teh key is tapped eg RIGHT will play the man walking and facing right (it’s ISOMETRIC)but if you HOLD the Key its to fast nd it loops the walk cycle to fast (it doesnt get off frame 1) whats a clever effecient way to fix this?

 
Comment by Trunk Monkey
2007-06-04 04:42:11

How do u make the bullets move downwards and also how do you make it so the bullets only hit the wall and not the whole stage?

 
Comment by bob Subscribed to comments via email
2007-06-22 10:39:22

how would i go about giving an instance name to a movie clip attached through ationscript?? this is holding me and my game back alot.

Heres the code i am using to attach the bullet, if that is any help
550){

this.removeMovieClip();
}
if (this._x

 
Comment by bob Subscribed to comments via email
2007-06-22 10:40:19

sry it screwed up alot.
that was my problem sry

Comment by awesty
2007-07-02 18:34:50

When you attach a MC it gives it an instace name. Example:

attachMovie(”ball”,”my_ball”,getNextHighestDepth());

Its instance name would be my_ball.

 
 
Comment by Kurt Subscribed to comments via email
2007-06-23 09:31:13

Awesty You have a spelling error but not in the tutorials the comment box where you put a or your website it says uri it looks like L but it’s I.

Comment by awesty
2007-07-02 18:35:21

It is supposed to be URI.

 
 
Comment by Drew
2007-07-02 11:52:22

This is kind of off topic, but could you make a tuturial on ragdoll physics?

Comment by awesty
2007-07-02 18:37:31

Possibly.

 
 
Comment by SaroVati Subscribed to comments via email
2007-08-25 06:07:16

Wow do I sound like a newb sry, but I got a problem :)
Lol first of all, the tutorial doesen’t seem to work for me :/ But do you need Flash MX 2004? My comp busted and I had to restart, and it only has Flash MX, big difference right? Cuz it’s either that, or Flash hates me. I at first read thru and wrote down codes, and I understand now. It didn’t work, so I copy and pasted. Still doesn’t work. I’ve done all your other tutorials, AI, AI2, RPG making, all the hard tuts, but this one doesen’t seem to click :P Help would be great lol

Comment by awesty
2007-09-10 17:31:05

Well Flash MX uses Actionscript 1, Flash MX 2004 + 8 use Actionscript 2 and Flash 9/CS3 uses Actionscript 3 (although you do have the option to use AS 2).

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-11 08:17:03

Hehe thought so :) Anyways ty :) Btw, if I make a file with Flash MX (not 2004) can I still change it around and open it when I get 2004 back? Or will it be a unidentifiable file again.

Comment by awesty
2007-09-11 08:36:11

Yes, you will be able to open it.

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-11 11:17:40

Yay :) While were at it, I’m trying to make ANOTHER game…. (friends ask too much at one time :() It’s now based on sports lol :P Tennis to be exact. Got lots of problems heh. I’ve sent u the e-mail, tell me whats wrong :) Problem is, when he swings the racket, the ball doesen’t get hit. It really makes me mad lol. Also, can u tell me how to make the balls shadow only appear when the ball is about 10 pixels away from it? I tried:

onClipEvent(load) {
this._alpha = 0;
}
onClipEvent(enterFrame) {
if (this._y = _root.ball._y+10) {
this._alpha = 100;
} else {
this._alpha = 0;
}
}

Ty :)

 
Comment by SaroVati Subscribed to comments via email
2007-09-11 11:29:28

Omg, I missed the other problem… If the ball goes in a direction too fast, the shadow can’t keep up….. Then the ball just falls thru, any way to fix that?

Comment by awesty
2007-09-11 16:56:26

Well to check if the ball is within 10 pixels of it you could use:

onClipEvent(load) {
this._alpha = 0;
}
onClipEvent(enterFrame) {
adj = this._x - _root.ball._x;
opp = this._y - _root.ball._y;
dist = Math.sqrt(Math.pow(adj,2)+Math.pow(opp,2));
if (dist <= 10) {
this._alpha = 100;
} else {
this._alpha = 0;
}
}

It isn’t test so it might not work.

I haven’t gotten your email yet. What address did you send it to?

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-12 08:07:28

AHHH Wrong email… just looked at front page… it switched :P I’ll resend it now

 
Comment by SaroVati Subscribed to comments via email
2007-09-12 10:41:50

OMG nvm, ur code didn’t work, but I got my new 1 to work :) All I did was change my balls code to:

this._x = _root.ball._x + _root.swingpower;

:) Ty anyways, help on the racket thing tho :( Can’t get it to work lol.

 
Comment by SaroVati Subscribed to comments via email
2007-09-13 09:50:05

AHHHHH I can’t open ur file for some reason…… Wtf? o.O I got the e-mail, is it for Flash MX? When I try to open it, I get an error message saying “Flash 6.0 r25 has encounted a problem and needs to close”…. Is it my version of Flash?

Comment by awesty
2007-09-13 16:51:08

Yep.

I have flash CS3 so the lowest flash version I can save it as is flash 8.

I will just email you the script.

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-14 08:23:13

Hm, the code looks exactly the same as the one on my ball… + It didn’t work when I put it on and I took my code off :( I was supposed to put ur code on the ball right…

Comment by awesty
2007-09-14 23:00:39

No, you said you had fixed the ball problem so I didn’t change it.

Put that code on the dude holding the tennis racket.

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-15 12:55:03

Uh… this is the code you sent me:

onClipEvent (load) {
vel_y = 15;
}
onClipEvent (enterFrame) {
this._x += _root.swingpower;
this._y -= vel_y;
vel_y -= 2;
if (vel_y

 
Comment by SaroVati Subscribed to comments via email
2007-09-15 12:57:28

Haha boy am I dumb :P here it is:

onClipEvent (load) {
vel_y = 15;
}
onClipEvent (enterFrame) {
this._x += _root.swingpower;
this._y -= vel_y;
vel_y -= 2;
if (vel_yLessThan=10) {
vel_y = -10;
}
if (this.hitTest(_root.ballshadow)) {vel_y = 15;this._y -= vel_y/2;
}
}

Comment by awesty
2007-09-15 15:59:43

Crap… I sent you the wrong one. I am sending the proper one now.

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-16 02:52:32

YAY IT WORKS WOOOOOOT. Btw, any thought come to mind about how I can make it so if I hit a smash, it goes faster? Just write another few lines of if statements right?

Comment by awesty
2007-09-16 10:24:48

Yep. But instead of having
_root.swingpower *= -1;

You could have
_root.swingpower *= -1.5;

So it goes faster as well as turning around.

 
 
Comment by SaroVati Subscribed to comments via email
2007-09-17 06:19:24

Yeah I did *= -2; Ty anyways tho :) Helped me LOADS! xD

 
Comment by Bryson Subscribed to comments via email
2007-10-31 14:59:47

Hey Awesty,
Some of the best tutorials here! I want to say thank you for everything you’ve done.

I’m currently making a tiny flash game based on two or three of your tutorials where you fly a helicopter (bound to the mouse) and you dodge bullets (I used the code in this tutorial) The problem I’m having is I can’t get the bullets to blow up the helicopter. Any help would be greatly appreciated, but if you don’t have time, that’s understandable as well.
Thanks for everything.
~Bryson

Comment by awesty
2007-10-31 15:16:13

if(_root["b"+n].hitTest(_root.heli)){
removeMovieClip(_root["b"+n]);
bullets.splice(j,1);
_root.heli.gotoAndStop(2);
}

Frame 2 of the helicopter could have an explosion animation that plays when it hits a bullet.

Comment by Bryson Taylor Subscribed to comments via email
2007-11-03 09:30:47

Works great! I guess I should of seen it was in the other code, though. ^_^ Feel a bit foolish. Thanks for your help!

 
 
 
Comment by Silviu Vlad
2007-11-15 07:49:51

I’m working on a small flash fight game(http://silviu.sytes.net/flash fight.html), and I want to know how to make my enemy(”Cernescu Marius”)to throw with blood when he’s toched by the attack movie clip of player character.
The key for this game is A,D , and (arrows) and numpad1. (SORRY FOR MY BAD ENGLISH)

 
Comment by Mike Subscribed to comments via email
2008-02-12 19:31:36

Hello,

I am contacting you on behalf of www.flashcomponents.net . I’ve read one of your tutorials and I like the way you write. Our site is continuously growing and we recently added a tutorial section. We kindly ask for your approval to allow us to publish your tutorials on our site, mentioning you as the author.
Of course, we are inviting you to do it yourself, but either way, it would be our pleasure to publish them.

Kind regards,
Mike | Flash Components Team

 
Comment by Luccaped Subscribed to comments via email
2008-05-16 04:51:20

But i want to do the same thing as Bryson but i want to blow up my spaceship. I put the same code as you put there but it didn’t work! is it my version of flash? my version is flash 8 professional or is it the registation point of the spaceship? please reply! because this problem stopped me from finishing my game! i was nearly finished!

 
Comment by Billy Subscribed to comments via email
2008-08-10 03:06:02

How would you make the bullets start at the top and fall down.

“_root[”b” n]._y -= 20;”

I changed the (y-=20) to (y =20) to make them descend but as the bullets start at the bottom they fall already out of site.

Also how do you increase the number of bullet on screen?

Many thanks.

 
Comment by Bigfoot Subscribed to comments via email
2008-09-12 05:43:50

@Billy
You would want to change that line :
_root[”b”+n]._y -= 20;
to
_root[”b”+n]._y += 20;
so that they move downwards.
But you also need to change where they start. Right now the last variable in line 5 (attachMovie(”Bullet…) is this :
_y:Stage.height
which says to attach the new clip at y:400 (or whatever the height of your movie is) You need to change that to
_y:0
if you want it to start at the very top, and then fall.
I hope that made sense.
Also, great tutorial! I tried doing this on my own and I’m sure it wasn’t nearly as clean as your script :)

 
Comment by Bigfoot Subscribed to comments via email
2008-09-12 05:49:52

Also @Billy
I changed the script to have more bullets on the screen by changing line 4
(if (random(10) = 0) {
and adding more numbers in there, so instead of just checking to see if it equaled 0, I did
(if (random(10) = 0 || 1 || 2 || 3) {
My script adds a new bullets if a random number between 0-9 equals 0, 1, 2 or 3 and I got a whole BUNCH of bullets at once.

 
Name (required)
E-mail (required - never shown publicly)
URI
Subscribe to comments via email
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> in your comment.