Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

javascript - How to trigger an event when elements (divs, images) touch each other?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...