Efficient Collision Detection with Dynamically Created MC’s
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).
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.
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
Flash 8
Give the wall an instance name of ‘wall’.
Now paste this script onto the frame.
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.
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.
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.
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.















Nice I’m first for once good tutorial
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)
http://www.awestyproductions.c.....-in-flash/
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
on(release){
gotoAndPlay(FrameNumber, “SceneName”);
}
on(release){
gotoAndStop(“SceneName”, FrameNumber)
}
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.
IT CAN NOT BE A COMPONENT BUTTON!
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)
Can you show me the current code?
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.)
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.
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
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?
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? =/
Well you need to attach them above the stage, instead of below and make there _y decrease instead of increase.
Ok not this again well I have to enter another message to view the message before.
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
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
Just email me at
sniper_rifle_048[@]hotmail[.]com
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?
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?
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
sry it screwed up alot.
that was my problem sry
When you attach a MC it gives it an instace name. Example:
attachMovie(”ball”,”my_ball”,getNextHighestDepth());
Its instance name would be my_ball.
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.
It is supposed to be URI.
This is kind of off topic, but could you make a tuturial on ragdoll physics?
Possibly.
Wow do I sound like a newb sry, but I got a problem
Help would be great lol
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
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).
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.
Yes, you will be able to open it.
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
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
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?
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?
AHHH Wrong email… just looked at front page… it switched
I’ll resend it now
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;
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?
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.
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…
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.
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
Haha boy am I dumb
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;
}
}
Crap… I sent you the wrong one. I am sending the proper one now.
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?
Yep. But instead of having
_root.swingpower *= -1;
You could have
_root.swingpower *= -1.5;
So it goes faster as well as turning around.
Yeah I did *= -2; Ty anyways tho
Helped me LOADS! xD
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
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.
Works great! I guess I should of seen it was in the other code, though. ^_^ Feel a bit foolish. Thanks for your help!
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)
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
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!
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.
@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
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.