Publishing System Settings Logout Login Register
Making an Object Bounce Around the Cursor
TutorialCommentsThe AuthorReport Tutorial
Tutorial Avatar
Rating
Add to Favorites
Posted on November 27th, 2006
8042 views
Adobe Flash
Making an object bounce around the cursor
Ben Fleming


Ever wondered how to make a ball swing around a mouse, like it was hooked on a rubber band? Probably not, but I'm going to show you how to do this anyway.
This is what you will be learning how to make:
File Download: The SWF

You're probably thinking, 'this is going to be complex!', but really it�s very simple. It just takes a few lines of code. So, open up Macromedia Flash, and start a new document. On the first layer, draw a circle with the oval tool (O), and fill it in with any colours you like.


Place it anywhere on the stage as its position doesn�t matter. Also, keep the circle pretty small. This is the object that will be swinging around on stage. Alright, now select your circle and convert it to a movieclip (Modify > Convert to Symbol... or F8). Name it Object or something, and convert it to a movieclip.


Also, give the ball an instance name of ball.
Ok, now that we've done that, we can start coding it. Name the layer you have to Object, and add a new layer. Name this one Actionscript, where, you guessed it, all our coding will go. Then, lock both layers as we've done the drawing part.


Now, click on the first frame of the Actionscript layer, and open up the actionscript panel (Windows > Actions or F9).
What we want to do first is declare some variables that will help us in the later code. What values this code uses though are:
      
  • Friction
  •   
  • Spring (stretchiness)
  •   
  • X velocity (X speed/movement)
  •   
  • Y velocity (Y speed/movement)

For our first two variables, friction and spring, write the following:

[code=Java]var friction:Number = .8;
var spring:Number = 4;[/code]

I used the most appropriate values for each. The friction is below 1 because it�s used to reduce our values later on. The spring is also used to reduce, but we're using it to divide something.

[code=Java]var vx:Number = 0;
var vy:Number = 0;[/code]

We made each zero because we are calculating the exact proper speed later.
Now that our variables are made, we need to make an onEnterFrame loop. So, in the next line, write:

[code=Java]onEnterFrame = function() {[/code]

Lets not delay this any longer; it's time for the formula. I will build up the formula so you can understand. In the next line write the following:

[code=Java]ball._x += _xmouse-ball._x;
ball._y += _ymouse-ball._y;
}[/code]

This is obviously not the complete formula. If you test it you'll see my point. All it does is set the balls x and y position to the mouse. But let�s look at the formula we have.


Here is a diagram of what we have. Hopefully this gives you some idea of what is going on at the moment. What we've calculated is the distance between the ball and the mouse, and added it onto the ball. This is continuously calculated, so that the ball always ends up at the mouse position. Now, what if we were to half the distance, or even put it into quarters? Well, let�s find out:

[code=Java]ball._x += (_xmouse-ball._x)/4;
ball._y += (_ymouse-ball._y)/4;[/code]

Now we've divided everything by 4. And if we're adding a quarter of the total distance between the ball and the mouse over and over onto the ball, we should get some sort of eased motion moving towards the mouse. Here's another diagram:


In this diagram we can see whets happening. The lines in bold are our new calculations (the amount we add) and the dotted lines are our old calculations (the actual distance). The new calculation gets smaller and smaller each time it�s added, because the distance between the mouse and the ball gets smaller and smaller aswell. Hopefully it�s not too hard to get your head around. So, test out those new lines of code. It's starting to take shape now.
Also, you've probably realised by now that the spring variable has the value of 4, the number used to divide our distance. That�s where our spring variable goes. So, replace '4' with spring:

[code=Java]ball._x += (_xmouse-ball._x)/spring;
ball._y += (_ymouse-ball._y)/spring;[/code]

Now, how do we get from what we have to what we want? Well, we need to get our x and y velocity variables into play. Replace the code we just wrote with:

[code=Java]vx += (_xmouse-ball._x)/spring;
vy += (_ymouse-ball._y)/spring;[/code]

Now our movement variables contain the speed. In the next line, write:

[code=Java]vx *= friction;
vy *= friction;[/code]

What we're doing here is reducing the values of each variable by 0.8. This is used so that our ball will eventually just spring to a stop on the mouse. You'll understand more, later. In the next line, write:

[code=Java]ball._x += vx;
ball._y += vy;[/code]

Here we're adding on the values to the ball. This is probably the toughest thing to make sense of in this tutorial, but let�s go through it.
First we've calculated the distance between the ball and the mouse inside a variable (_xmouse-ball._x). Then we've divided that distance and added onto the variable (vx += (_xmouse-ball._x)/spring;). Then, we've reduced that variable even more with friction (vx *= friction;), to eventually slow down the ball. Then, after that we've continuously added that onto the ball (ball._x += vx;). Now you're thinking that the ball has got to move, but how does it work so realistically? Well, when the ball moves past the mouse, and either from a negative to a positive number, or a positive to a negative, then straight away the value from vx and vy will start to reduce. If our friction was 1, or we didn�t have any friction, then the vx and vy variables will just keep reducing, or increasing, until it reaches an exact opposite number of the largest point it reached. That would mean it would just keep going and never stop. That�s why we have friction; so that it does get smaller and it does eventually stop. So, you've probably trying to swallow this whole thing at once. Try not to, you'll probably choke. Instead take little bits of my explanation and try them out separately, and try to understand it in your own way.
Here's the whole code so far in case you missed anything:

[code=Java]var spring:Number = 4;
var friction:Number = 0.8;
var vx:Number = 0;
var vy:Number = 0;
onEnterFrame = function () {
    vx += (_xmouse-ball._x)/spring;
    vy += (_ymouse-ball._y)/spring;
    vx *= friction;
    vy *= friction;
    ball._x += vx;
    ball._y += vy;
}[/code]

Not much, not much at all. Infact, its only 12 lines long. Still, we're not done. We actually need a string for the ball to swing on! Don�t worry, it doesn�t affect our code (well, you should've realised that before), but it looks kind of funny without one. To make a line, or a string, from the mouse to the ball we need to make an empty movieclip first. So, after the second-last line (ball._y += vy;) write the following:

[code=Java]this.createEmptyMovieClip("line", 0);[/code]

What this does is it creates a dynamic movieclip called line, with a depth of 0. The depth is what I like to call, "actionscripted layers". They determine the distribution of it. Unfortunately when creating dynamic movieclips the lowest depth is 0, except it stays on top of anything hand-drawn (static). Anyway, write this next:

[code=Java]line.clear();[/code]

Here we're treating the new movieclip like it was a movieclip. We use its name as its instance, and give it things to do. Only these things to do are a bit different to normal movieclips. Here we're clearing everything that's been put into that movieclip. Yes, I know nothing is in the movieclip, but for what we're writing next, it will be necessary. Write:

[code=Java]line.lineStyle(1, 0x000000, 50);
line.moveTo(ball._x, ball._y);
line.lineTo(_xmouse, _ymouse);[/code]

Ok, here we're dynamically making the line to sit inside our line movieclip. First we've set the lines style (lineStyle). Here we have 3 parameters, but there are actually a lot more than just 3. I've only filled out the 3 necessary ones, which are (in order) thickness, colour, and alpha. I've set our thickness to 1, our colour to black, and our alpha to 50%. After that, we've made the starting point as to where the line is drawn from. This requires two parameters, x and y position. We've set it to the ball. Then, the lineTo method actually draws the line to the mouse position.
Back to the clear() method. We use this because here we're continuously drawing lines, and not removing them. So we use clear to remove the last drawn line, so it looks like we're just using 1 line the whole time.
Now go on, test it out. Here's the entire code:

[code=Java]var spring:Number = 4;
var friction:Number = 0.8;
var vx:Number = 0;
var vy:Number = 0;
onEnterFrame = function () {
    vx += (_xmouse-ball._x)/spring;
    vy += (_ymouse-ball._y)/spring;
    vx *= friction;
    vy *= friction;
    ball._x += vx;
    ball._y += vy;
    this.createEmptyMovieClip("line", 0);
    line.clear();
    line.lineStyle(1, 0x000000, 50);
    line.moveTo(ball._x, ball._y);
    line.lineTo(_xmouse, _ymouse);
}[/code]

By the looks of it we're done!

Thankyou for taking my tutorial, and I hope you learnt from it.
Ben.
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