Question

I'm appending the results to the wrapper to see if it's getting the right positions. It works fine for the player div(#redbox). However it doesn't update the closest enemy div's(.shd) position.

Full code here : http://jsfiddle.net/2bbW5/ Just move down and right with arrow keys and you'll see how it prints the same enemy position every time, but prints the new player position correctly each time.

$('.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');

What am I doing wrong in that it doesn't update the closest enemy div's position in relation to #redbox?

Était-ce utile?

La solution

.closest() won't tell you which sibling is physically closest to another element. You need to compute that yourself.

Here's one approach that uses .each() to compute and store the distance to each enemy, then .filter() to reduce the set of siblings to the closest enemy:

    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/

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top