I have two array with object. Example:
var boxes = [],
coins = [],
k = 0;
boxes.push({
x: 300,
y: 350,
width: 500,
height: 500
});
for (k; k < 30; k++) {
coins.push({
x: Math.floor(Math.random() * (10 - 4) + 4) * 100,
y: Math.floor(Math.random() * (4 - 1) + 1) * 100,
width:25,
height:25
});
}
After that I use for
for draw those things. The problem is that sometimes the coins will drawn in boxes. How to check if coins are in boxes range? I was thinking about calculating the square boxes and coins but I have no idea how to finish that.
var i = 0,
j = 0;
for (i; i < coins.length; i++) {
for (j; j < boxes.length; j++) {
if (boxes[j].x + boxes[j].width /* something */ coins[i].x + coins[i].width && boxes[j].y + boxes[j].height /* something */ coins[i].y + coins[i].height) {
/* do nothing */
} else {
ctx.fillRect(coins[i].x, coins[i].y, coins[i].width, coins[i].height);
}
}
}
Does anybody know how to finish that? Or maybe there is any other way? I can use only pure JavaScript.
Thank you for help.
Here is the if condition to get a hit:
if (
(boxes[j].x < (coins[i].x + coins[i].width) && (boxes[j].x + boxes[j].width) > coins[i].x) &&
(boxes[j].y < (coins[i].y + coins[i].height) && (boxes[j].y + boxes[j].height) > coins[i].y)
) {
/* HIT - Do nothing */
} else {
/* No Hit - Draw the coin */
}
I didn't test it, but I'm sure it works ...
EDIT:
By the way, I noticed you are not re-setting i
and j
var in the for
loops, you should do that at least with the second loop ( j
), otherwise loop it will not work.
for (i = 0; i < coins.length; i++) {
for (j = 0; j < boxes.length; j++) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.