У меня есть два объектаОбнаружение столкновений в переходе
var player = document.getElementById("player");
var ahead= document.getElementById("follower");
document.addEventListener("click", move_player);
function move_player(e) {
x_click = e.clientX;
y_click = e.clientY;
player.style.transition = "all 0.5s"
if (x_click < canvas.clientWidth && y_click < canvas.clientHeight){
player.style.left = x_click - player.clientWidth/2 + "px";
player.style.top = y_click - player.clientHeight/2 + "px";
}
var for_ahead = setInterval(function(){ move_ahead() }, 20);
function move_ahead() {
ahead.style.left = x_click - ahead.clientWidth+ "px";
ahead.style.top = y_click - ahead.clientHeight +"px";
ahead.style.transition = "all 1.4s"
}
Представьте меня есть объект, и когда я нажимаю где-то там идет. Второй объект следует за кликом, но с меньшей скоростью. Этот объект столкнется, если первый объект не будет двигаться в ближайшее время.
Я пытаюсь создать обнаружение столкновений между этими двумя объектами с помощью:
if(((parseInt(player.style.left) < parseInt(ahead.style.left) + parseInt(ahead.clientWidth))) &&
parseInt(player.style.left) + parseInt(player.clientWidth) > parseInt(ahead.style.left) &&
parseInt(player.style.top) < parseInt(ahead.style.top) + parseInt(ahead.clientHeight) &&
parseInt(player.style.top) + parseInt(player.clientHeight) > parseInt(ahead.style.top))
Я добавил функцию выше в for_ahead.
var for_ahead = setInterval(function(){ move_ahead() }, 20);
function move_ahead() {
if(((parseInt(player.style.left) < parseInt(ahead.style.left) + parseInt(ahead.clientWidth))) && parseInt(player.style.left) + parseInt(player.clientWidth) > parseInt(ahead.style.left) &&
parseInt(player.style.top) < parseInt(ahead.style.top) + parseInt(ahead.clientHeight) && parseInt(player.style.top) + parseInt(player.clientHeight) > parseInt(ahead.style.top)) alert("Detected collision");
ahead.style.left = x_click - ahead.clientWidth*2.6+ "px";
ahead.style.top = y_click - ahead.clientHeight/2 +"px";
ahead.style.transition = "all 1.4s"
}
Моя проблема заключается в том, что после того, как он вычисляет ahead.style.left и ahead.style.top всплывает предупреждение («Обнаружено столкновение») Он не рассчитывает обнаружение столкновений в каждый момент переход. Как я могу это сделать?