This article mainly introduces how to use JS to determine the collision. examples show how to use js to determine the object collision and related applications, if you need it, refer to the examples in this article to describe how to determine the collision of JavaScript. Share it with you for your reference. The details are as follows:
JS collision judgment method:
The Code is as follows:
/** Determine whether a collision exists
* @ Param obj original object
* @ Param dobj: target object
*/
Function impact (obj, dobj ){
Var o = {
X: getDefaultStyle (obj, 'left '),
Y: getDefaultStyle (obj, 'top '),
W: getdefastyle style (obj, 'width '),
H: getDefaultStyle (obj, 'height ')
}
Var d = {
X: getDefaultStyle (dobj, 'left '),
Y: getDefaultStyle (dobj, 'top '),
W: getdefastyle style (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 all vertices are in two 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 Attributes
* @ Param obj object
* @ Param attribute
*/
Function getDefaultStyle (obj, attribute ){
Return parseInt (obj. currentStyle? Obj. currentStyle [attribute]: document. defaultView. getComputedStyle (obj, false) [attribute]);
}
Example:
The Code is as follows:
Demo