转换中的碰撞检测

时间:2015-05-03 17:39:10

标签: javascript transition

我有两个对象

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后,它会弹出警报(&#34;检测到碰撞&#34;) 它不会在转换的每个时刻计算碰撞检测。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

element.style.left返回left属性的目标值,您需要使用getComputedStyle来获取当前样式值。

我准备了简单的小提琴来展示如何使用jQuery和VanillaJS获取当前样式值。

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