Publishing System Settings Logout Login Register
Ball Collision and Movement
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on December 4th, 2006
14683 views
Adobe Flash
Ball Collision and Movement
Ben Fleming

The first step is to set up a new Flash document. For this example, keep your dimensions at default (550x400). Create a new movieclip with a regerstration in the centre, and call it 'ball'. Inside that movieclip, draw a 24x24 circle without an even colour (you'll see why later). Drag the ball onto the main stage, and call its instance name 'ball' also. Name the layer it is in 'Ball' again. Create a new layer and call it 'Actions'. Here is where we will stick all of the coding for it to bounce off the walls. Click on the first frame of the timeline or the Actions frame, and open up the actions panel. For all you people out there that just need the code, well here it is:

[code=Java]    xmov = 5;
    ymov = 5;
    rotation = 10;
    stagewidth = 538;
    stageheight = 388;
    _root.onEnterFrame = function() {
        ball._x += xmov;
        ball._y += ymov;
        ball._rotation += rotation;
        if(ball._x < 12) {
            ball._x = 12;
            xmov *= -1;
        } else if(ball._x > stagewidth) {
            ball._x = stagewidth;
            xmov *= -1;
        } else if(ball._y < 12) {
            ball._y = 12;
            ymov *= -1;
        } else if(ball._y > stageheight) {
            ball._y = stageheight;
            ymov *= -1;
        } else if(ball._y < 12 && ball._x > stagewidth) {
            ymov *= -1;
            xmov *= -1;
        } else if(ball._y > stageheight && ball._x < 12) {
            ymov *= -1;
            xmov *= -1;
        }
    }[/code]

But if you actually want to learn how to create this, just continue to read on. We'll break this code into seperate parts.

[code=Java]    xmov = 10;
    ymov = 10;
    rotation = 20;[/code]

This is replacing all the values we are going to use with words, so its easier to edit later. Its not compulsory, but I'd strongly reccommend that you would use these. xmov = 10; is for the speed of the ball moving in a horizontal line. You can change the value of xmov to speed up or slow down the ball. ymov = 10; is just the same, yet this moves the ball in a vertical line. If these values are the same, the ball will always bounce at a perfect diagonal line. If either of the values are different to the other, they will change in their angle. So say if I set xmov to 5 and ymov to 0, I would get a fairly slow horizontal bounce going, but now angle in the movement. But if I kept the values exactly the same, they will always be at a 45 degree angle always. For the last one, rotation = 10;, that is the speed of the rotation of the ball. That speed is an accurate speed mesurement for the speeds of x and y. The rotation is always the x speed + the y speed, if we are talking about normal speeds. Your probably thinking, "Why didnt you just do 'rotation = xmov+ymov;'?". The reason why is that the rotation doesnt have to be reasonable. Because say if you through a ball up in the air, and you powered its spin fast, the speed of that spin would equal no where near the the speed of the x and y speeds. So you could use just about any speeds for the ball and anything could be possible (well, if you keep it in reason. Like moving a ball at the speed of light is quite impossible now adays). Thats all about that part of the code. Moving on...

[code=Java]    stagewidth = 538;
    stageheight = 388;[/code]

This is basically whats happened before, about replacing words for numbers ect. Right now your using basic algebra, you know? Because thats basically what algebra is. Words for numbers, well, letters for numbers mostly. The stage width is, well, the stage width; 550px. But because the ball is 24x24, you half the width of the ball in half, then subtract that from the actual stage width. Why do we do that? Becuase when you created the ball at the start, we set the regerstration as the centre, so the ball only reacts to the edges when the center hits. So it only bounces, when the middle of the ball hits the boundaries. Thats why we subtract half the balls width from the stage width and height, because half the ball goes over the boundaries. So if you make a bigger ball, you'll have to repeat this proccess to get a realistic looking collision. This is just about the same thing that happens with the stageheight = 388; part, so no explaining for that (Yippie!).

[code=Java]    _root.onEnterFrame = function() {
        ball._x += xmov;
        ball._y += ymov;
        ball._rotation += rotation;[/code]

This is where it starts to get into the movement of the ball. The top part, _root.onEnterFrame = function() { is telling us that the following code will be continiously called, therefore creating the movement in the ball. The _root part is telling it (the following code) that this is all happening on the main stage (not inside a movieclip). The onEnterFrame code is telling it that the code will only be played when that frame is entered. The function() { area is telling us that the following is a function that will be continiously called (Which I said before). If you ever use this again, the following code is always ended with a closing squiggly bracket (}), to know that the function ends at that point. ball._x += xmov; is for the ball to move in a horizontal way. See how we're using xmov instead of 10? Good. ball._x is telling us that the balls x (x = horizontal movement) will be moved xmov (10) pixels at each calling. Using += is for adding it. If i just used = it would just change the balls x to that position. I could use -= to subtract too, but not in this example. Your've probably figured what the rest do, if you could read. ball._y += ymov; that adds ymov pixels vertically and ball._rotation += rotation; this adds 20 pixels in a rotation movement.

[code=Java]        if(ball._x < 12) {
            ball._x = 12;
            xmov *= -1;
        }[/code]

This is the first part to the collision. Its telling us that if the balls x position is lower than 12, set the balls x to 12, and reverse the movement of the balls x. So the ball._x < 12 is saying (on its own) that the balls x is below 12. But were saying in the whole script there that if it is what I just said, then xmov multiply by -1, so we will get the exact oppisite number, therefore reversing its movement. Because a negative times a positive equals a negative. But your probably thinking, "What will happen when the ball has already encountered that and reversed the speed, now xmov is negative, and it happens again?". Well a negative by a negative is a positive, so the ball will always reverse its speed with a negative one. The * is a times symbol in flash, just for your knowledge. Remember a } always has to be put down after a function, and that if statement is a function. Going back to the top, why do you think we say 12? Because thats one boundary for the ball. The edges on the left and top are always 0. So then why do we put 12 instead of 0? Because remember up around the top we said we subtract half the ball from the stage width and height? Well, for these edges we add them. So basically all around there is an invisible square that is 12px from the actual edges in the stage for the ball to hit. The reason why we set the balls x to 12, is because this is what makes a perfect collision. Because its saying, that if it reaches its limit, it will set it to that x position. But why? Well, since its moving by a certain amount of pixels each time round, its not going to hit an edge at that exact pixel, it will most definately be a bit over. So using that code will prevent the ball from moving straight through the wall.

[code=Java]        } else if(ball._y < 12 && ball._x > stagewidth) {
            ymov *= -1;
            xmov *= -1;
        }[/code]

You probably know how the other parts works, so now onto here. This code is pretty much exactly like before, but theres an else part, and an extra statement. This one is telling us if the balls y is lower than 12 and the balls x is larger than the stagewidth (538), then reverse ymov and xmov's values. This code isnt compulsory, its just so that incase it happens and there can be flaws, it wont stuff up. The else part isnt compulsory either, its just that it connects all the if statements into one. It also makes it that only 1 if statement can happen at a time. So instead of:

[code=Java]        if(ball._x < 12) {
            ball._x = 12;
            xmov *= -1;
        } else if(ball._x > stagewidth) {
            xmov *= -1;
        }[/code]

We could have:

[code=Java]        if(ball._x < 12) {
            ball._x = 12;
            xmov *= -1;
        }
        if(ball._x > stagewidth) {
            ball._x = stagewidth;
            xmov *= -1;
        }[/code]

Just simplifying it all for you. That is all for this tutorial, and I hope I have taught you something usefull in your flash future. Thanks for taking this tutorial!
Dig this tutorial?
Thank the author by sending him a few P2L credits!

Send
Ben

This author is too busy writing tutorials instead of writing a personal profile!
View Full Profile Add as Friend Send PM
Pixel2Life Home Advanced Search Search Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Tutorial Index Publish Tutorials Community Forums Web Hosting P2L On Facebook P2L On Twitter P2L Feeds Pixel2life Homepage Submit a Tutorial Publish a Tutorial Join our Forums P2L Marketplace Advertise on P2L P2L Website Hosting Help and FAQ Topsites Link Exchange P2L RSS Feeds P2L Sitemap Contact Us Privacy Statement Legal P2L Facebook Fanpage Follow us on Twitter P2L Studios Portal P2L Website Hosting Back to Top