Reputation: 3512
Working on a project where objects move around the screen randomly. I'm trying to have a element at the top that does not get covered by these objects. This is my current code:
function makeNewPosition(){
// Get viewport dimensions
var h = $(window).height() - 150;
var w = $(window).width() - 100;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
This works well but I'm needing to block off, lets say 150px at the top of the screen where the objects cannot go. For some reason I have been unable to do this. How would I modify my code to accomplish this?
Thanks for any help!
Upvotes: 0
Views: 56
Reputation: 12452
You need to set the 150px
as offset from top. Otherwise the bottom
150px of your screen will be untouched by the objects, not the top
.
function makeNewPosition() {
var h = $(window).height() - 150;
var w = $(window).width() - 100;
var nh = Math.floor(Math.random() * h) + 150;
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
If you want to let the left and right area of 100px
to be untouched too, you need to substract 200px
and add 100px
to the result.
function makeNewPosition() {
var h = $(window).height() - 150;
var w = $(window).width() - 200;
var nh = Math.floor(Math.random() * h) + 150;
var nw = Math.floor(Math.random() * w) + 100;
return [nh,nw];
}
Upvotes: 1
Reputation: 42746
You need to add the 150 to your random height, that way no matter what the random number is generated your nh
is going to start at least 150
var nh = Math.floor(Math.random() * h) + 150;
Upvotes: 1