2015-10-01 12 views
9

Mam część gry, w której kursor ma "zwolnić", gdy przechodzi nad niektórymi elementami div. Używam funkcji, która może wykryć kolizję z div. Działa to dobrze, gdy kursor napotka pierwszy element div, ale nie działa on wcale na drugim elemencie div.Funkcja JavaScript wpływa tylko na pierwszy div z klasą

Check out this jsFiddle dla lepszego zrozumienia tego, o czym mówię. Przekaż kursor nad pierwszym białym blokiem (class='thing') po lewej stronie i zwolni. Przekaż kursor nad drugim blokiem (także class='thing') i nic się nie dzieje. Potrzebuję tej funkcji kolizji do pracy na wszystkich elementach div, gdzie class='thing'.

HTML

<div id='cursor'> 
      &nbsp; 
     </div> 
     <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 350px; right: 800px; z-index: -1;'> 
      &nbsp; 
     </div> 
     <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 200px; right: 400px; z-index: -1;'> 
      &nbsp; 
     </div> 

JS

(function collide(){ 
var newInt = setInterval(function() { 
function collision($cursor, $thing) { 
    var x1 = $cursor.offset().left; 
    var y1 = $cursor.offset().top; 
    var h1 = $cursor.outerHeight(true); 
    var w1 = $cursor.outerWidth(true); 
    var b1 = y1 + h1; 
    var r1 = x1 + w1; 
    var x2 = $thing.offset().left; 
    var y2 = $thing.offset().top; 
    var h2 = $thing.outerHeight(true); 
    var w2 = $thing.outerWidth(true); 
    var b2 = y2 + h2; 
    var r2 = x2 + w2; 

    // change 12 to alter damping higher is slower 
    var varies = 12;  

    if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){ 
    } else { 
    varies = 200; 
    console.log(varies); 
    } 
$xp += (($mouseX - $xp)/varies); 
    $yp += (($mouseY - $yp)/varies); 
    $("#cursor").css({left:$xp +'px', top:$yp +'px'}); 

} 

$(collision($('#cursor'), $('.thing'))); 
//$('.result').text(collision($('#cursor'), $('.thing'))); 

}, 20); 
})(); 
+0

$ rzeczą jest zbiorem – mplungjan

+3

Unikaj używania 'setInterval 'dla animacji, ponieważ może powodować (i, faktycznie, w przyczynach JSFiddle) opóźnienia. Użyj 'window.requestAnimationFrame'. –

+0

http://sourceforge.net/p/jquerycollision/code/ci/master/tree/jquery-collision.js – mplungjan

Odpowiedz

12

$thing to zbiór elementów, jak chcesz, ale tutaj jest problem, że pytasz konkretnych atrybutów z $thing jak offset().left;, który nie może zwrócić więcej niż jednego numeru, dlatego po prostu bierze pierwszy. Zamiast tego należy użyć funkcji .each(), aby zapętlić wszystkie elementy w $thing.

$thing.each(function(index, element){ 
    //your code for each thing here 
}); 
+0

Dzięki za pomoc. To działa teraz. Wydaje mi się, że wpadłem na coś, co wydaje się być błędem. Jeśli przyjrzeć się tej zaktualizowanej jsfiddle: [link] (https://jsfiddle.net/5sy1tg36/8/) Zobaczysz: 'if (b1 b2 < y2 || y1 > || R1 < x2 || x1 > r2) { waha = 200; changeMouseSpeed ​​(); } else { waży = 12; changeMouseSpeed ​​(); console.log ("hit"); } ' Ale jeśli zmienię wartości w' varies', to w ogóle nie będzie działać. –

+0

Czy możesz zadać to osobne pytanie? Brzmi interesująco! –

+0

Być może powinieneś umieścić 'varies' poza pętlą. –

8

Po wybraniu elementu przez nazwę klasy (w przypadku używając .thing) w jQuery można uzyskać szereg elementów i funkcji collision() weźmie pierwszy element w tablicy. więc do przezwyciężenia tego trzeba jednoznacznie wybrać zarówno elementy można to zrobić za pomocą identyfikatora jako selektor, można zmienić swój kod jak poniżej, aby go działa zgodnie z oczekiwaniami

<div id='track'> 
    <div class = 'container'> 
     <div id='cursor' class='cursor'> 
      &nbsp; 
     </div> 
     <div class='thing' id="a1" style='width:70px; height:70px; background: #fff; position: absolute; bottom: 175px; right: 400px; z-index: -1;'> 
      &nbsp; 
     </div> 
     <div class='thing' id="a2" style='width:70px; height:70px; background: #fff; position: absolute; bottom: 100px; right: 200px; z-index: -1;'> 
      &nbsp; 
     </div> 
    </div> 
</div> 


(function cursorMapping(){ 

var $mouseX = 0, $mouseY = 0; 
var $xp = 0, $yp =0; 

$(document).mousemove(function(e){ 
    $mouseX = e.pageX; 
    $mouseY = e.pageY;  
}); 

function showCoords(event) { 
    var x = event.clientX; 
    var y = event.clientY; 
    var coor = "X: " + x + ", Y: " + y; 
} 

var timestamp = null; 
var lastMouseX = null; 
var lastMouseY = null; 

var mrefreshinterval = 500; // update display every 500ms 
var lastmousex=-1; 
var lastmousey=-1; 
var lastmousetime; 
var mousetravel = 0; 
var lastmousetravel = 0; 

var speed; 
var marker1 = 1; 
var marker2 = 1; 

var timer = setInterval(function(){ 
    marker1; 
    marker2; 
}, 20); 

$(function() { 

    var $speedometer = $('#speed'), 
     _speed = 0; 

    $('#track').cursometer({ 
     onUpdateSpeed: function thisSpeed(speed) { 
      _speed = speed; 
      $speedometer.text(Math.ceil(speed * 100)/100); 
     }, 
     updateSpeedRate: 20 
    }); 

}); 

var thisInterval = setInterval(function FXInterval(){ 
    speed = $('#speed').text(); 
     $('#cursor').css({'background-color': '#CE7A7A'}); 
}, 20); 

$('html').mousemove(function(e) { 
    var mousex = e.pageX; 
    var mousey = e.pageY; 
    if (lastmousex > -1) 
     mousetravel += Math.max(Math.abs(mousex-lastmousex), Math.abs(mousey-lastmousey)); 
    lastmousex = mousex; 
    lastmousey = mousey; 
    var speed = lastmousex + lastmousey; 

    setTimeout(function(){ 
     lastmousetravel = mousetravel; 
    }, 20); 
}); 

(function collide(){ 
var newInt = setInterval(function() { 
function collision($cursor, $thing) { 
    var x1 = $cursor.offset().left; 
    var y1 = $cursor.offset().top; 
    var h1 = $cursor.outerHeight(true); 
    var w1 = $cursor.outerWidth(true); 
    var b1 = y1 + h1; 
    var r1 = x1 + w1; 
    var x2 = $thing.offset().left; 
    var y2 = $thing.offset().top; 
    var h2 = $thing.outerHeight(true); 
    var w2 = $thing.outerWidth(true); 
    var b2 = y2 + h2; 
    var r2 = x2 + w2; 

    // change 12 to alter damping higher is slower 
    var varies = 12;  

    if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){ 
    } else { 
    varies = 200; 
    console.log(varies); 
    } 
$xp += (($mouseX - $xp)/varies); 
    $yp += (($mouseY - $yp)/varies); 
    $("#cursor").css({left:$xp +'px', top:$yp +'px'}); 
} 
$(collision($('#cursor'), $('#a1'))); 
$(collision($('#cursor'), $('#a2'))); 

}, 20); 
})(); 

})(); 
+0

Dzięki za pomoc! Jest to zdecydowanie najbardziej bezpośrednie rozwiązanie mojego problemu. Jednak użyję '.each()', ponieważ jestem mniej zaznajomiony z tym i to jest dobre dla mnie, aby wypróbować różne rzeczy. –

Powiązane problemy