views:

97

answers:

1

Anyone have a good idea for a method of achieving random floaty motion? Like, just general smooth drift in a constrained area.

This is what I tried:

var rangeX = 100;
var rangeY = 100;
var gravity = .001;

$('.floating').each(function() {
    $(this).data('startX', $(this).position().left);
    $(this).data('startY', $(this).position().top);
    $(this).data('velocityX', 0);
    $(this).data('velocityY', 0);
    chooseDestination();
});

setInterval(function() {
    $('.floating').each(function() {
        var changeX = ($(this).data('destinationX') - $(this).position().left) * gravity;
        var changeY = ($(this).data('destinationY') - $(this).position().top) * gravity;

        var velocityX = $(this).data('velocityX') + changeX;
        var velocityY = $(this).data('velocityY') + changeY;

        $(this).data('velocityX', velocityX);
        $(this).data('velocityY', velocityY);

        $(this).css('left', $(this).position().left + velocityX);
        $(this).css('top', $(this).position().top + velocityY);
    });
}, 10);

setInterval(chooseDestination, 2000);

function chooseDestination() {
    $('.floating').each(function() {
        $(this).data('destinationX', $(this).data('startX') - rangeX/2 + Math.random() * rangeX);
        $(this).data('destinationY', $(this).data('startY') - rangeY/2 + Math.random() * rangeY);
    });
}

It really doesn't look very floaty though.

+1  A: 

"Floaty" generally requires slow changes in velocity. What I would do, from a high-level perspective, is set up an acceleration/velocity/position model for movement, where your random generator affects acceleration only. You already have the other two layers. Establish limits for velocity and acceleration at any given point in time (I'd limit absolute distance, not just distance in X and Y), and don't update the rate of acceleration every frame. Lastly, deal in fractional values for velocity and acceleration, which will be turned into an integer position change only at the last minute when you're drawing the object's new position. What you'll end up with is an object that will slowly head off in one direction, then start drifting in a different direction, maybe stop and hover for a second, then start going again.

KeithS
Hmm. Food for thought. I definitely need to combine a limit in distance with a minimum distance as well, to prevent it occasionally getting stuck in the same place for too long.
Joren