2012-02-22 5 views
1

У меня есть эта игра, которую я пишу с помощью jQuery Collision, и она использует клавиши клавиатуры для перемещения div, когда div касается другого div, он должен предотвращать перекрытие.jQuery Collision

Как я могу это сделать?

HTML ----

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 

    <link href="style.css" rel="stylesheet" /> 

    <script src="jquery.min.js" rel="javascript"></script> 
    <script src="game.js" rel="javascript"></script> 
    <script src="jquery-collision-1.0.1.js" rel="javascript"></script> 
    <script src="jquery-ui-draggable-collision-1.0.1.js" rel="javascript"></script> 

</head> 
<body> 

<div id="office"> 

    <div class="popup"> 
     <p>hello desk</p> 
     <a class="close">X</a> 
    </div> 

    <div class="chris"></div> 

    <!--Rian, Peter, Chris, Christopher ---------------- DESK --> 
    <div class="desk-full" style="position: absolute; right: 50px; top: 50px;"> 

     <div class="christopher-stuff"></div> 

    </div> 

    <!--Adrian, Tatam, Ellize ---------------- DESK --> 
    <div class="desk-full" style="position: absolute; right: 50px; top: 300px;"> 

    </div> 

</div> 

</body> 
</html> 

JAVASCRIPT ----

$(document).ready(function(){ 

$(".chris").click(function(){ 

var KEY = { 
    UP: 38, 
    DOWN: 40, 
    LEFT: 37, 
    RIGHT: 39 
} 

// a global object to store all global variable used for the game 
var office = { 
} 

// an array to remember which key is pressed and which is not. 
office.pressedKeys = []; 

$(function(){ 
    // set interval to call gameloop every 30 milliseconds 
    office.timer = setInterval(gameloop,30); 

    // mark down what key is down and up into an array called "pressedKeys" 
    $(document).keydown(function(e){ 
     office.pressedKeys[e.keyCode] = true; 
    }); 
    $(document).keyup(function(e){ 
     office.pressedKeys[e.keyCode] = false; 
    }); 
}); 

// this function is called every 30 milliseconds 
function gameloop() 
{ 
    moveMe(); 
    collideDetection(); 
} 

function moveMe() 
{ 

    if (office.pressedKeys[KEY.UP]) // arrow up 
    { 
     var direction = parseInt($(".chris").css("top")); 
     $(".chris").css({ 
       top: direction-5, 
       background: "url(chris-top.gif) no-repeat !important", 
       width: "43px", 
       height: "44px" 
      }); 
    } 
    if (office.pressedKeys[KEY.DOWN]) // arrow down 
    { 
     var direction = parseInt($(".chris").css("top")); 
     $(".chris").css({ 
      top: direction+5, 
      background: "url(chris-down.png) no-repeat !important", 
      width: "48px", 
      height: "25px" 
      }); 
    } 
    if (office.pressedKeys[KEY.LEFT]) // left 
    { 
     var direction = parseInt($(".chris").css("left")); 
     $(".chris").css({ 
      left: direction-5, 
      background: "url(chris-left.gif) no-repeat !important", 
      width: "43px", 
      height: "44px" 
      }); 
    } 
    if (office.pressedKeys[KEY.RIGHT]) // right 
    { 
     var direction = parseInt($(".chris").css("left")); 
     $(".chris").css({ 
      left: direction+5, 
      background: "url(chris-right.gif) no-repeat !important", 
      width: "43px", 
      height: "44px" 
      });   
    } 



     if (office.pressedKeys[KEY.UP] & office.pressedKeys[KEY.RIGHT]) // arrow up 
    { 
     $(".chris").css({ 
       background: "url(chris-top-right.png) no-repeat left top !important", 
       width: "43px", 
       height: "44px" 
      }); 
    } 
     if (office.pressedKeys[KEY.UP] & office.pressedKeys[KEY.LEFT]) // arrow up 
    { 
     $(".chris").css({ 
       background: "url(chris-top-left.png) no-repeat !important", 
       width: "43px", 
       height: "44px" 
      }); 
    } 
     if (office.pressedKeys[KEY.DOWN] & office.pressedKeys[KEY.RIGHT]) // arrow down 
    { 
     $(".chris").css({ 
       background: "url(chris-down-right.png) no-repeat !important", 
       width: "43px", 
       height: "44px" 
      }); 
    } 
     if (office.pressedKeys[KEY.DOWN] & office.pressedKeys[KEY.LEFT]) // arrow down 
    { 
     $(".chris").css({ 
       background: "url(chris-down-left.png) no-repeat !important", 
       width: "43px", 
       height: "44px" 
      }); 
    } 
} 

function collideDetection(){ 
    var chrisY = parseInt($(".chris").css("top")); 
    var chrisX = parseInt($(".chris").css("left")); 

    var chrisY = chrisY + 50; 
    var chrisX = chrisX + 50; 

    // -------------------- jQuery Collision Dtection and Prevention of Overlapping --------------------- 
    var hit_list = $(".chris").collision({ obstacle: ".desk-full", preventCollision: true }); 

    var officeHeight = parseInt($("#office").height()); 
    var officeWidth = parseInt($("#office").width()); 

    if(shipX <= 0) { 
     $(".chris").css({ 
      left: "0", 
      background: "url(chris-right.png) no-repeat !important", 
      width: "25px", 
      height: "48px" 
     }); 
     } 

    if(chrisX > officeWidth) { 
     $(".chris").css({ 
      left: "0px", 
      background: "url(chris-left.png) no-repeat !important", 
      width: "25px", 
      height: "48px" 
     }); 
     } 

    if(chrisX <= 0) { 
     $(".chris").css({ 
      top: "0", 
      background: "url(chris-down.png) no-repeat !important", 
      width: "48px", 
      height: "25px" 
     }); 
     } 

    if(chrisY > officeHeight) { 
     $(".chris").css({ 
      top: "0px", 
      background: "url(chris-up.png) no-repeat !important", 
      width: "48px", 
      height: "25px" 
     }); 
     } 
} 

});  
}); 

ответ

6

Вы можете использовать JQuery Collision и JQuery UI Draggable Collision.

JQuery Расширение Collision возвращает столкновения между двумя селекторами. Ручки дополняют, поля, границы и могут определять перекрытие или часть снаружи.

С JQuery Столкновение вы можете найти все перекрывается:

var list = $("#selector").collision(".obstacle"); 

Возвращает список всех элементов, которые перекрывают друг друга "#selector".

С JQuery UI Draggable, вы можете связать событие при перетаскивании элемента и столкновение происходит, и вы можете предотвратить столкновение:

$("#selector").draggable({ obstacle: ".obstacle", preventCollision: true }); 

Другие плагины для обнаружения столкновений:
Collidable Draggables,
Collision Check Plugin v1.1,
$.event.special.drop

также: Detect overlapping with JavaScript

+0

эй, спасибо за ответ. Я пробовал это раньше, но он не обнаруживает столкновения ... – Christopher

+0

@ Кристофер, какой из них вы проверили? –

+0

все, я тестирую каждый, посмотрю на мой код – Christopher