Sunday, 22 August 2010

rotation drag in action script

/* sets the starting point for the maths that follows */
var objectnewdeg = 0;
var objectdeg = 0;
var mindeg = 0;
var maxdeg = 300;
/* this function rotates the object live as the user drags */
rotateobject = function () {
/* this checks whether the user is rotating within the max and min rotation factors defined in the variables above, it only allows rotation if it is within the set limits, otherwise the object won't move */
if (objectnewdeg>=mindeg && objectnewdeg<=maxdeg) {
curpoint = _xmouse;
objectnewdeg = objectdeg+(curpoint-objectstartdeg);
_root.object_mc._rotation = objectnewdeg;
}
};
/* This starts the object rotation function and sets the starting point of the user's click - all rotation is then based on the difference between where the user first clicks and where they drag to */
_root.object_mc.onPress = function() {
objectstartdeg = _xmouse;
objectrotInterval = setInterval(rotateobject, 10);
};
/* This stops the rotation as soon as the user let's go. It also checks that the user has not been able to drag further than the min or max limits before the code could correct them, and if they have, adjusts the rotation to fit within the limit boundaries */
_root.object_mc.onRelease = function() {
clearInterval(objectrotInterval);
if (objectnewdegmaxdeg) {
_root.object_mc._rotation=maxdeg;
objectnewdeg = maxdeg;
}
objectdeg = objectnewdeg;
};
/* This is the same as the function above, but executes if the user has drifted off the object when they stop dragging */
_root.object_mc.onReleaseOutside = function() {
clearInterval(objectrotInterval);
if (objectnewdegmaxdeg) {
_root.object_mc._rotation=maxdeg;
objectnewdeg = maxdeg;
}
objectdeg = objectnewdeg;
};


While this code may have more lines, it's much simpler to follow. In addition it also allows you to set a maximum and minimum rotation factor, so you can set how far you want the user to be allowed to rotate the object in either direction.

To use it, simply paste it into frame 1, and create and MovieClip on the stage with the instance name 'object_mc'.

No comments: