Interactive Spin Actionscript Tutorial

I have been thinking of different interactions that are possible with objects. If you’ve read this blog at all you’ll know that I’ve played with physics and gravity and throwing balls and bouncing balls and all sorts. But I hadn’t wrapped my head around an interactive spinner. I know it’d be easy to make a slider or something that would apply a spin to an object, but this just isn’t interactive enough for me.

Circle with slider to rotate and button for random spin:

Get Adobe Flash player

This attempt at spinning is ok. I mean, it spins the object and it even glides to a stop if you press the button for a random spin… But it’s just not intuitive and not fun. But if you want this, here’s how I did it.

Actionscript:

drag = .96;
speed = 0;

slider.handle.onPress = function() {
spinning = false;
//drag along the line
this.startDrag(true, slider.line._x-slider.handle._width/2, slider.line._y-slider.handle._height/2, slider.line._width-slider.handle._width/2, slider.line._y-slider.handle._height/2);
}
slider.handle.onRelease = slider.handle.onReleaseOutside = function() {
this.stopDrag();
}
_root.onEnterFrame = function() {
if (spinning) {
//apply the speed to the rotation
knob._rotation += speed;
//recalculate speed
speed = speed*drag;
//if speed gets unnoticeably tiny just set it to 0
if (Math.pow(speed, 2) < .0001) {
speed = 0;
}
}
else {
//set the rotation from the slider position
knob._rotation = slider.line._x + slider.handle._x + slider.handle._width/2;
}

//spit out feedback continuously
feedbackr.text = knob._rotation;
feedbackaccr.text = speed;
}
spinner.onRelease = function() {
//find a random speed
speed = (Math.random()* 50) - 25;
spinning = true;
}

I want to grab it and spin it though. I want to apply the same principles from physics, like acceleration and friction as forces to the object, so I can grab to spin and release to watch it glide gracefully to a stop. I’ve been thinking about this and how I’d have to use trigonometry and stuff to do it. One day I finally had the time and tried it out. It took me a minute but I figured out that what I needed was arctangent. So (with pointers from jbum, thanks Jim!) I came up with this:

Interactive grab-able circle to spin and twirl:

Get Adobe Flash player

This one is much more interactive and intuitive. I really think this is because there are no sliders or buttons, no controls, just an object to interact with. It’s much more like real life!

Steps:

In order to make a grab and spin object
1. You have to know where you grab. The user clicks on the shape (knob) and you must figure out what degree or rotation point they have started at. (atan2)
2. As the knob is clicked and the mouse moves (dragging), calculate new rotation by mouse position
3. When mouse is released figure out the current speed of rotation and apply it to the knob with friction, so it can be thrown and spun in that way. (Of course this is optional, if you just want to spin it when the mouse is down you’re done at step 2)

Actionscript:

damp = .96; //friction
r = 0; //rotation
accr = 0; //speed of rotation

knob.onPress = function() {
dragging = true;
//find mouse y coordinate in relation to knob origin
a = _root._ymouse - knob._y;
//find mouse x coordinate in relation to knob origin
b = _root._xmouse - knob._x;
//using arctangent find the spot of rotation (in degrees)
oldr = Math.atan2(a,b)*180/Math.PI;
}

knob.onRelease = knob.onReleaseOutside = function() {
dragging = false;
}

knob.onEnterFrame = function() {
if (dragging) {
//find mouse y coordinate in relation to knob origin
a = _root._ymouse-knob._y;
//find mouse x coordinate in relation to knob origin
b = _root._xmouse-knob._x;
//using arctangent find the spot of rotation (in degrees)
r = Math.atan2(a,b)*180/Math.PI;

//use current rotation and previous rotation
//to find acceleration
//averages the acceleration with the
//previous acceleration for smoother spins
accr = ((r - oldr) + accr)/2;
//apply the acceleration to the rotation
knob._rotation += accr;
//remember current rotation as old rotation
oldr = r;
feedbacka.text = a;
feedbackb.text = b;
}
else {
knob._rotation += accr;
//apply friction to acceleration force
//and if acceleration gets tiny, just set it to zero
if (Math.pow(accr, 2) > .0001 ) {
accr *= damp;
}
else{
accr = 0;
}
}
//spit out feedback continuosly
feedbackr.text = knob._rotation;
feedbackaccr.text = accr;
}

I commented the code to explain what is happening, if you need more just post a comment. Let me know if you find this useful and what you end up making with it.

Downloads:

spin.fla and interactiveSpin.fla

This entry was posted in portfolio, tutorial and tagged , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

14 Comments

  1. Posted March 17, 2008 at 1:24 am | Permalink

    Hi Evan

    Grab the knob and rotate it all the way around for one revolution without letting go.

    There is a rather violent movement when the user rotates the knob all the way through x < 0 and when y passes through 0 (positive to negative or negative to positive). It jumps to the other side (180 deg away) and then rapidly comes back again.

    I would suggest not using atan2 and using only sine to determine your rotation.

  2. Posted March 17, 2008 at 10:11 am | Permalink

    Thanks for catching that Zac, I hadn’t noticed that hiccup in there…
    It seems to be when it is calculating the acceleration as you drag through the negative x-axis (from the origin of the knob). It’s because I’m using the difference between old rotation and current rotation to find the acceleration (line 32), and when oldr is -179 and new is 180 that makes for quite a bit of acceleration… accr = ((r – oldr) + accr)/2; … it helps I guess that it’s averaged with the old accr, but it doesn’t correct it by any means.
    When I have some time I’ll have to get in and map the accr calculation correctly to see the values as circular, … 178, 179, 180, -179, -178 …

  3. Posted May 24, 2008 at 4:58 pm | Permalink

    Here’s a fix, albeit not perfect, to the above mentioned problem. Within the onEnterFrame actions, find the line that says:

    accr = ((r-oldr)+accr)/2;

    and change it to this….

    if (r-oldr > 160 || r-oldr < -160){
    accr = ((0)+accr);
    }else{
    accr = ((r-oldr)+accr)/2;
    }

    I’m in the process of implementing this code into a project. When it’s ready I’ll try to remember to link it.

  4. Craig
    Posted July 1, 2008 at 10:56 pm | Permalink

    thanks you guys both. This is perfect for what i am doing. (making tutorials for a gas-fitting school), i am going to try apply this rotation to one of the gas taps. Just have to figure out how to make a ‘maximum’ amount of turns.

  5. Gerald
    Posted October 6, 2008 at 8:23 pm | Permalink

    Great tutorial. One question, how would I make the knob only spin a certain degree? Say if I wanted this to be a volume knob and would want it to only spin a certain degree as if turning the knob on a speaker amplifier. Thanks!

  6. Damion Murray
    Posted February 24, 2009 at 10:54 am | Permalink

    There are two solutions to the rotation problem. One involves using vector math to find angular displacements by first mapping flash’s piece-wise rotational range of [0, -180][180, 0] to the standard [0, 360] rotational range typically used in math, applying the Vector Dot Product to find the smaller angle between two vectors and finally determining the direction of rotation (clockwise or counter-clockwise). This is the most robust solution since it is based on standard mathematical models of rotation. But most Flash Developers coming from a design background may have trouble grappling with its more technical aspects. The second, more accessible solution involves exploiting the relationships between nested clips. But that’s all I am going to say on the matter. Half the fun is figuring stuff out for oneself.

  7. rihamfathy
    Posted April 7, 2009 at 10:06 am | Permalink

    i have a question!!
    how can i make the object 3d and move it in all directions
    (if i have a footage of anything such as a mobile and i want to make it 3d) how can i modify this script to do what i want??
    thanks in advanced…

  8. Posted May 8, 2009 at 12:48 pm | Permalink

    Thank you, Evan. I have looking for a navigation wheel that I could spin and this is perfect for it.

  9. munaji
    Posted June 23, 2010 at 9:35 am | Permalink

    thanks for the lesson

  10. von
    Posted July 13, 2010 at 4:06 pm | Permalink

    Hi,
    could you convert this to as3-if you have a chance?

  11. Daniel
    Posted July 23, 2010 at 10:38 am | Permalink

    Hi,

    I’m currently trying to use the rotator but would like to set it so the circle can only turn to half-way (turn 180 degrees) and no further.
    If there is any chance you could be of assistance it would be a great help.

    Thankyou

    • Posted August 2, 2010 at 9:40 am | Permalink

      @von – I have this on my list to convert to as3, it’s only a matter of affording the time to do it and then remembering to post it ;)

      @Daniel- You would just need to set the limits and add a clause around the lines that apply the rotation transformation. Check to see if it would cause the value to go out of bounds and reel it back in if needed. Looks like lines 34 and 41. Best of luck

      • RANJAN MANI
        Posted September 22, 2011 at 1:16 am | Permalink

        Hello Evans,
        I need a help from you……..
        I am in the process of creating a rotating knob with push function……
        how to program both rotate and press function in to single object in AS3…….Please help…..

  12. Posted November 12, 2010 at 9:03 pm | Permalink

    Hello,

    This is a great example, but do you have an AS3 version?

    Thanks
    Garrett

One Trackback

  1. By [Flash CS3] - Drehknopfprobleme ... - Flashforum on January 8, 2010 at 6:29 am

    [...] hab grad beim suchen folgenden Link gefunden: Interactive Spin Actionscript Tutorial | circlecube Vielleicht hilft dir das weiter. Greets Schnetty __________________ Chaos ist nur eine [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Recent Posts

    Developing for old browsers is (almost) a thing of the past – (37signals)

    Basecamp announces that it’s new version will not support old browsers! They will of course continue to support them in their “classic” version. But this is good news and as more implement this type of policy the internet will be happy. It used to be one of the biggest pains of web development. Juggling different [...]

    Screen shot 2012-02-10 at 12.59.33 PM

    Vendor Prefixes – about to go south

    What are “standards” coming to? Who’s guilty? Apple and Chrome: They’re supporting vendor prefixed properties like they’re a standard part of development. Firefox, Opera and Internet Explorer: They should have been on the ball more. Need to push their evangelism further. Teach developers that it’s not exclusively -webkit to style elements. All the browsers: experimental [...]

    bio

    An Event Apart Notes: Ethan Marcotte, Responsive Web Design

    Ethan Marcotte has become the father of Responsive Web Design and spent this whole day focused on principles, techniques, gotchas, examples, … all about building and how to build responsive sites. With a sprinkle of mobile first. For Ethan, it all started with this article: http://www.alistapart.com/articles/dao/ Think of architecture, the whole design phase is established [...]

    Webcomm_Montreal

    An Event Apart Notes: Jared Spool, The Curious Properties of Intuitive Web Pages

    Senseless waste of asterisks… Avis used an asterisk to denote optional fields. This means that there is a lot of baggage that comes with an asterixk. Somewhere this symbol got meaning, it’s not in the bible! We can control when something goes from unintuitive to intuitive. A design is intuitive (although technically and grammatically speaking [...]

    untitled-158-2

    An Event Apart Notes: Marco Arment, Bridging the App Gap

    The iPhone changed our industry in 2007: first mobile to have a desktop class web browser and it made people start using their mobile phones as computers! All apps other than apple provided ones were web browser apps. Most of the first apps were branded web browsers. No real difference between using mobile site or [...]

    lukew_space

    An Event Apart Notes: Luke Wroblewski, Mobile to the Future

    MASS MEDIA (in waves) Print, Recordings, Cinema, Radio, Television, Internet, Mobile Mobile is the new Mass Media It certainly is mass and massive. More mobile devices (by far) every day than babies born on the planet. Mobile devices are eating into our personal computing shares. New waves of mobile media eat all previous media waves. [...]

    IMG_4500

    An Event Apart Notes: Josh Clark, Buttons are a Hack

    Mobile and touch should be revolutionizing design and user experience. We don’t want to touch a tiny link or button. Back button is just stupid. Fitz’s Law, make things fat proximal targets for easy touching. People are lazy, let’s as designers LET people be lazy! Maybe even use the whole screen as your control. Eliminate [...]

    nicole_pink_bkg_2012

    An Event Apart Notes: Nicole Sullivan, Our Best Practices are Killing Us

    Grep to for analyze css. CSS duplication is a web-wide problem. Started helping facebook optimize thier site and they had 1.9MB of css loading. The same color showing up hundreds of times. Many many color statements and declarations. !important declarations get dangerous. Sites found to have over 500 !important declarations! float is a serious problem [...]

    ericmeyer

    An Event Apart Notes: Eric Meyer, The Future of CSS

    Cormorant trained to fish for the fishermen. The fishermen tie bands around the birds necks that are. Fishermen fish at night, using lamps they attract bugs, which attract fish, and the cormorant get to fish but cant swallow them and the fishermen take the fish. Browser vendors are promising us new CSS tools, but don’t [...]

    sammyj

    An Event Apart Notes: Ethan Marcotte, Rolling Up Our Responsive Sleeves

    Henry Adams (Descendant of 2 presidents: great-grandson to John Adams and grandson to John Quincy Adams). He lived between the civil war and world war 1. He witnessed the industrial revolution. Chaos was the law of nature, Order was the dream of man Samuel Johnson – funniest man in the 17th Century… Responsive Design: 1. [...]

  • Recent Comments

    me-gamer

    me-gamer

    this is really nice. this made many of my task simple.
    Lori Newman

    Lori Newman

    Just wanted to thank you for your presentation. It was extremely informative and just what I...
    Karl

    Karl

    I have been using for some time this nice Banner, from developer FX. They have a really nice Live...
    Karl

    Karl

    Thank you for this wonderful link… recommend it! Fast, simple, easy… :-)
    Gabriel

    Gabriel

    Hi Valerie, I don’t know if you are still following this post, but I tried seeing if it is...
    avinash

    avinash

    Hi Evan, I am using the same code and trying it on chrome/firefox it is not working on neither...