Collision detection during transition

I have two objects

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"
}

      

Imagine I have an object and when I click somewhere it goes there. The second object follows the click, but at a slower speed. This object will collide if the first object does not move soon.

I am trying to create collision detection between these two objects using:

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))

      

I added the function above to 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"
}

      

My problem is that after it calculates forward.style.left and forward.style.top, it throws a warning ("Collision Detected") It doesn't calculate collision detection at every transition moment. How can i do this?

+3


source to share


1 answer


element.style.left

returns the target value of the property left

you need to use getComputedStyle

to get the current style value.

I have prepared a simple script to show how to get the current style values ​​using jQuery and VanillaJS.



http://jsfiddle.net/zg69gdh9/2/

+1


source







All Articles