2014-01-07 58 views
0

我將結果附加到包裝上,看它是否獲得了正確的位置。它適用於玩家div (#redbox)。但它不會更新最接近的敵方div的(.shd)位置。獲取keydown上最接近的兄弟姐妹的位置

Full code here:http://jsfiddle.net/2bbW5/用箭頭鍵向下和向右移動,你會看到它每次打印同一個敵人位置,但每次都能正確打印新的玩家位置。

$('.gamewrapper').on('keydown', function (event) { 
     var a = event.which; 
     var b = parseInt($x.css('left'), 10); 
     var c = parseInt($x.css('top'), 10); 
     var player_position = $('#redbox').position(); 
     var enemy_position = $('#redbox').siblings().closest('.shd').position(); 
     $('<p> Player position is : ' + player_position.left + ' and ' + player_position.top + '</p>').appendTo('.gamewrapper'); 
     $('<p> Enemy position is : ' + enemy_position.left + ' and ' + enemy_position.top + '</p>').appendTo('.gamewrapper'); 

我在做什麼錯的,因爲它不最接近敵人div的相對位置更新爲#redbox

+0

我不認爲你首先是正確設置敵方位置 – andi

回答

1

.closest()不會告訴你哪個兄弟是身體最接近另一個元素。你需要自己計算一下。

下面是一個使用.each()計算和距離存儲每個敵人,然後.filter()減少兄弟節點集到最近的敵人一個辦法:

var player_position = $('#redbox').position(); 
    var closest_dist = Number.POSITIVE_INFINITY; // largest number in JavaScript 
    var enemy_position = $('#redbox').siblings('.shd').each(function() { 
     var epos = $(this).position(); 
     var dist = Math.sqrt(Math.pow(player_position.left - epos.left, 2) + Math.pow(player_position.top - epos.top, 2)); // basic distance formula 
     $(this).data('dist', dist); // easier than building an array 
     closest_dist = Math.min(closest_dist, dist); // update the closest_dist variable 
    }).filter(function() { 
     return $(this).data('dist') - closest_dist < 0.001; // allow for floating-point errors 
    }).first().position(); // use .first() since there might be more than one 

http://jsfiddle.net/ApY46/