Random Movement in a Fixed Container
- by James Barracca
I'm looking to create something that can move randomly inside of a fixed div container. I love the way the object moves in this example that I found searching this website...
http://jsfiddle.net/Xw29r/15/
The code on the jsfiddle contains the following:
$(document).ready(function(){
animateDiv();
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({ top: newq[0], left: newq[1] }, speed, function(){
animateDiv();
});
};
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest/speedModifier);
return speed;
}?
CSS:
div.a {
width: 50px;
height:50px;
background-color:red;
position:fixed;
}?
However, I don't believe the code above constricts that object at all. I need my object to move randomly inside of a container that is let's say for now... 1200px in width and 500px in height.
Can someone steer me in the right direction? I'm super new to coding so I'm having a hard time finding an answer on my own.
Thanks so much!
James