Linked Questions

Popular Questions

Programming Floaty Motion

Asked by At

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.

Related Questions