我的代码中有一个if语句,如下所示。当我在控制台日志中检查这两个元素相互冲突时,if语句变为true,但不会停止我的interval函数。我想知道是什么原因导致它无法正常工作?
var animationTimer = setInterval(bladAnimation, 30);
document.onkeydown = function(event) {
if (event.keyCode == 37) {
// <--
fx = -15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 38) {
// opp
fy = -15;
fx = 0;
froskAnimation()
}
if (event.keyCode == 39) {
// -->
fx = 15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 40) {
// ned
fy = 15;
fx = 0;
froskAnimation()
}
}
function froskAnimation() {
Xfrosk = fx + Xfrosk;
Yfrosk = fy + Yfrosk;
if ((Yfrosk + 70 > maxY) || (Yfrosk < minY)) {
Yfrosk = Yfrosk - fy;
}
if ((Xfrosk + 70 > maxX) || (Xfrosk < minX)) {
Xfrosk = Xfrosk - fx;
}
frosk.style.left = Xfrosk + "px";
frosk.style.top = Yfrosk + "px";
console.log(Xfrosk)
}
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
}
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
答案 0 :(得分:2)
加载JavaScript时,该条件仅执行一次。那时条件可能是错误的。您应该在bladAnimation的末尾移动它(我想您要做的是在碰到另一个移动块时停止其移动)。
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
}