JS implements the collision judgment method, and js implements collision
This article describes how to implement collision determination in JavaScript. Share it with you for your reference. The details are as follows:
JS collision judgment method:
Copy codeThe Code is as follows:/** determines 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:
Copy codeThe Code is as follows: <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Title> demo </title>
<Style type = "text/css">
Body {margin: 0px ;}
. Main {position: relative ;}
# F1 {position: absolute; background: # FF0000; top: 100px; left: 100px; width: 200px; height: 200px; z-index: 999}
# F2 {position: absolute; background: # FFFF00; top: 0px; left: 0px; width: 600px; height: 150px ;}
</Style>
</Head>
<Body>
<Div class = "main">
<Div id = "f1"> </div>
<Div id = "f2"> </div>
</Div>
<Script type = "text/javascript">
Var o = document. getElementById ("f1 ");
Var d = document. getElementById ("f2 ");
Alert (impact (o, d ));
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;
}
}
Function getDefaultStyle (obj, attribute ){
Return parseInt (obj. currentStyle? Obj. currentStyle [attribute]: document. defaultView. getComputedStyle (obj, false) [attribute]);
}
</Script>
</Body>
</Html>
I hope this article will help you design javascript programs.