The example in this article describes the method of determining collision in JS. Share it with everyone for your reference. The details are as follows:
JS collision method:
/**Determine whether there is a collision
* @param obj original object
* @param dobj target object
*/
function impact(obj, dobj) {
var o = {
x: getDefaultStyle(obj, 'left'),
y: getDefaultStyle(obj, 'top'),
w: getDefaultStyle(obj, 'width'),
h: getDefaultStyle(obj, 'height')
}
var d = {
x: getDefaultStyle(dobj, 'left'),
y: getDefaultStyle(dobj, 'top'),
w: getDefaultStyle(dobj, 'width'),
h: getDefaultStyle(dobj, 'height')
}
var px, py;
px = o.x <= d.x ? d.x : o.x;
py = o.y <= d.y ? d.y : o.y;
// Determine whether the points are in both objects
if (px >= o.x && px <= o.x o.w && py >= o.y && py <= o.y o.h && px >= d.x && px <= d.x d.w && py >= d.y && py < = d.y d.h) {
return true;
} else {
return false;
}
}
/**Get object properties
* @param obj Object
* @param attribute attribute
*/
function getDefaultStyle(obj, attribute) {
Return parseInt(obj.currentStyle ? obj.currentStyle[attribute] : document.defaultView.getComputedStyle(obj, false)[attribute]);
}
An example is as follows:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn