如何在元素(div,图像)彼此接触时触发事件? [英] How to trigger an event when elements (divs, images) touch each other?

查看:99
本文介绍了如何在元素(div,图像)彼此接触时触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道触发jquery事件(显示a的内容)何时可以触发,进入,传递等另一个元素(一个包含另一个图像的div)。



我正在玩使用Javascript,CSS和HTML制作一个愚蠢的小游戏,并且我试图弄清楚如何部署事件,就像.click()或任何其他字符(图像)接触或进入另一个元素(带有图像的div)。我得到了使用w,a,s,d移动的角色(一个图像元素),并且我希望它在触摸某事物时触发事件。

解决方案

我必须在这里做一些假设。你有对象A,它正在使用wasd键移动,并且你有对象B和C.你已经有一个事件,它监听按键并移动对象A.移动对象A后,你需要计算A的边界(左,右,上,下),并与对象B和对象C的边界进行比较。

您可以使用$ element.offset()顶部,然后右边是+宽度,底部是顶部+高度。

因此,一旦你对所有对象都有这个对象,就会相交:

  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<亮;
RightOverlap = a.right> b.left&& a。 b.left;
aVerticalOverlay = b.top> a.top&& b.bottom< a.bottom;
Horizo​​ntalOverlay = b.left> a.left&& b.right< a.right; ((aTopOverlap || aBottomOverlap || aVerticalOverlay)&&(aLeftOverlap || aRightOverlap || aHorizo​​ntalOverlay)){
//碰撞逻辑
}



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.

解决方案

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
}

这篇关于如何在元素(div,图像)彼此接触时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆