tags:

views:

846

answers:

5

I have created a small game, in which some blocks are move around a main div. The mouse which also holding a div (I had assigned the position of cursor to that div).

I just want to trace out, whether the cursor div is moving over the blocks(those are also div). If it comes like that then the game will be over.

How can I detect whether the block or cursor div moves over each other?

+1  A: 

This is not a straightforward task using plain javascript, because you have to trace the div's ancestry and sum the relative positions until you find an absolutely positioned div.

On the other hand, this task is quite trivial with a javascript library such as jQuery or Prototype. In jQuery, for example, $(myDiv).offset() returns the div's position relative to the document.

If you also include jQuery UI, and make your main div a "Draggable", and all other divs "Droppable", all you need is hook up on the Droppable's over event to get notified when the main div is dragged over the other one.

David Hanak
+2  A: 

If you're using jQuery, you can find the left, top, width and height of a div by using these:

$(myDiv).offset().left
$(myDiv).offset().top
myDiv.offsetWidth
myDiv.offsetHeight

Use those to work out the left, right, top and bottom of each div. Then two divs overlap each other if:

left1 < right2 && left2 < right1 && top1 < bottom2 && top2 < bottom1
teedyay
A: 

The concept you're talking about is called collision detection.

Very simply, you need to get the bounds of your div and then loop through all the blocks to see if they overlap.

Greg
A: 

getBoundingClientRect()

John Resig has a great article here: getBoundingClientRect is Awesome

Gary Green
A: 

If you don't want to use jQuery you can copy/paste from here (LGPL code); http://code.google.com/p/ra-ajax/source/browse/trunk/Ra/Js/Ra.js

The place to look for is the "absolutize" function at line no. 220 which recursively calculates the size of "ancestor nodes" in the while loop.

Pasted in here for references;

var valueT = this.offsetTop  || 0;
var valueL = this.offsetLeft  || 0;
var el = this.offsetParent;

while (el) {
  Ra.extend(el, Ra.Element.prototype);
  if( el.tagName == 'BODY' ) {
    break;
  }
  var pos = el.getStyle('position');
  if( pos == 'relative' || pos == 'absolute') {
    break;
  }
  valueT += el.offsetTop  || 0;
  valueL += el.offsetLeft || 0;
  el = el.offsetParent;
}

"this" here is a DOM element...

However I suspect that what you have is absolutely positioned divs inside another div with position:relative in which case you can just use;

var y = parseInt(myElement.style.top, 10);
var x = parseInt(myElement.style.left, 10);

which will be orders of magnitudes faster then doing the "offset loops"...

Thomas Hansen