我有两个动画元素。第一个是从上到下的动画。而第二个元素是从左到右动画。我如何检测这些元素何时碰撞?我创建了一个示例 http://jsfiddle.net/6XQ4Q/3/
$(".container, .pool").height(800);
setInterval(function () {
randomWave();
}, 3000);
function randomWave() {
var wave = $(".wave");
var waveItem = wave.find(".waveItem");
var number = waveItem.length;
var random = Math.floor((Math.random() * 3));
waveItem.removeClass("active");
waveItem.eq(random).addClass("active");
if ((waveItem.eq(random).hasClass("right"))) {
$(".kid").animate({
left: "-=50"
});
}
if ((waveItem.eq(random).hasClass("left"))) {
$(".kid").animate({
left: "+=50"
});
}
}
setInterval(function () {
droppingCoin();
}, 6000);
function droppingCoin() {
//var newq = makeNewPosition();
$(".coin").animate({
top: 800,
opacity: "toggle"
}, 5000, "linear", function () {
$(this).css({
top: "-15px"
}).show();
});
}
答案 0 :(得分:2)
这似乎有效:
var delta = ($(".coin").width() + $(".kid").width()) * 0.5 ;
var x1 = $(".coin").offset().left,
y1 = $(".coin").offset().top,
x2 = $(".kid").offset().left,
y2 = $(".kid").offset().top;
if (x1 >= x2 - delta && x1 <= x2 + delta &&
y1 >= y2 - delta && y1 <= y2 + delta)
{
$(".kid").css({"background": "blue"}); // HIT!
} else {
$(".kid").css({"background": "red"}); // No hit...
}
var r1 = $(".coin").width() / 2, // "Radius" of .coin
x1 = $(".coin").offset().left, // x position
y1 = $(".coin").offset().top, // y position
r2 = $(".kid").width() / 2, // "Radius" of .kid
x2 = $(".kid").offset().left, // x position
y2 = $(".kid").offset().top, // y position
dx = x2 - x1, // Difference in horizontal position
dy = y2 - y1, // Difference in vertical position
L = Math.sqrt(dx * dx + dy * dy), // Distance between
step = r1 + r2 - L; // Amount of overlap
if(step > 0) { // There's a collision if step > 0
$(".kid").css({"background": "blue"});
} else {
$(".kid").css({"background": "red"});
}