Kinetic scrolling in AS3

I have a container movieclip that contains my "game" and I would like to be able to drag the "camera" (i.e. the container clip) around, but I need it to have kinetic movement, i.e. feel more like native dragging and scrolling on an iOS device.

I can't seem to find anything that deals with this properly and in the manner that I am looking for, and I also would prefer to stay away from using any 3rd party packages if there are licenses involved. This is for personal side projects that may or may not see a form of commercial release, so I would rather a) learn how to code this myself and b) not have to rely and pay for third party libraries.

Any help would be greatly appreciated.

Thanks!

-

To get a feeling of inertia you could average the velocities of the last few frames of dragging, and then set the speed of the camera to that when the user lets go.

Something like this:

``````static const BUFFER_LENGTH:int = 3;
static const FRICTION:Number = 0.95;

var dxBuffer:Vector.<Number>;
var dyBuffer:Vector.<Number>;

var lastX:Number;
var lastY:Number;

public function startDrag(x:Number, y:Number) {
dxBuffer = new Vector.<Number>();
dyBuffer = new Vector.<Number>();
for (var i:int = 0; i < BUFFER_LENGTH; i++) {
dxBuffer.push(0);
dyBuffer.push(0);
}
lastX = x;
lastY = y;
camera.velocityX = 0;
camera.velocityY = 0;
}

public function updateDrag(x:Number, y:Number) {
dxBuffer.shift();
dyBuffer.shift();

dxBuffer.push(lastX-x);
dyBuffer.push(lastY-y);

camera.x += lastX - x;
camera.y += lastY - y;

lastX = x;
lastY = y;
}

public function releaseDrag() {
// Set camera velocity to average buffer value
var avgdx:Number = 0;
var avgdy:Number = 0;

for each (var dx : dxBuffer) {avgdx += dx}
for each (var dy : dyBuffer) {avgdy += dy}

avgdx /= BUFFER_LENGTH;
avgdy /= BUFFER_LENGTH;

camera.velocityX = avgdx;
camera.velocityY = avgdy;
}

public function updateCamera {
// Update camera, to be called on each frame
camera.x += camera.velocityX;
camera.y += camera.velocityY;

camera.velocityX *= FRICTION;
camera.velocityY *= FRICTION;
}
``````

Then to get a nice smooth slow down you can just multiply the velocity by a friction constant, 0.95 or so. You might want to increase the friction at very low speeds to get it to rest quicker.

-