0

I would like to know if it is at all possible to trigger a jquery event (showing contents of a ) when an element (an image) touches, enters, passes over etc. another element (a div containing another image).

I am playing around making a stupid little game using only Javascript, CSS, and HTML, and I'm trying to figure out how to deploy an event, just like .click(), or any other when the character(the image) touches or enters over another element(a div with an image in it). I got the character (an image element) to move around using w, a, s, d and I want it to trigger events when it touches something.

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
Suiu
  • 11
  • 1
  • 1
    Welcome to Stack Overflow! It is expected that you at least attempt to code this for yourself. Stack Overflow is not a code writing service. I would suggest that you do some additional research, either via Google or by searching SO, make an attempt and. if you still have trouble, come back with **your code** and explain what you have tried and why it did not work. – Paulie_D Jun 08 '16 at 14:17
  • http://stackoverflow.com/questions/5419134/how-to-detect-if-two-divs-touch-with-jquery – DaniP Jun 08 '16 at 14:18
  • Yes it is possible. – Redu Jun 08 '16 at 14:19

1 Answers1

0

I have to make some assumptions here. You have object A, which is moving with wasd keys, and you have objects B and C. You already have an event which listens for wasd key press and moves object A. After you move object A, you need to calculate the bounds of A (left, right, top, bottom) and compare with the bounds of object B and object C.

You can use $element.offset() to get the left and top, then right is left + width and bottom is top + height.

So once you have that for all objects, object intersect:

aTopOverlap = a.top > b.top && a.top < b.bottom;
aBottomOverlap = a.bottom > b.top && a.bottom < b.bottom;
aLeftOverlap = a.left > b.left && a.left < b.right;
aRightOverlap = a.right > b.left && a.right < b.left;
aVerticalOverlay = b.top > a.top && b.bottom < a.bottom;
aHorizontalOverlay = b.left > a.left && b.right < a.right;

if ((aTopOverlap || aBottomOverlap || aVerticalOverlay) && (aLeftOverlap || aRightOverlap || aHorizontalOverlay)) {
    //collision logic here
}
Mark Evaul
  • 653
  • 5
  • 11
  • 1
    This is all pseudo code. You would need to fill in the pieces to collect the bounds of all objects and then loop through to determine collisions with each object individually. – Mark Evaul Jun 08 '16 at 14:25