写一些封装part1 (事件绑定移除,圆形矩形碰撞检测)

时间:2024-05-05 20:35:38
var EventHandle = {
addEvent:function(ele,type,handle){
if (ele.addEventListener) {
ele.addEventListener(type,handle,false);
}else if(attachEvent){
ele.attachEvent("on"+type,handle);
}else{
ele["on"+type]=handle;
}
},
deleteEvent:function(ele,type,handle){
if (ele.removeEventListener) {
ele.removeEventListener(type,handle,false);
}else if(detachEvent){
ele.detachEvent("on"+type,handle);
}else{
ele["on"+type]=null;
}
}
}

//事件封装函数

function hitFun(obj1, obj2) {
var l1 = obj1.offsetLeft;
var t1 = obj1.offsetTop;
var b1 = t1 + obj1.offsetHeight;
var r1 = l1 + obj1.offsetWidth; var l2 = obj2.offsetLeft;
var t2 = obj2.offsetTop;
var r2 = l2 + obj2.offsetWidth;
var b2 = t2 + obj2.offsetHeight;
if(l1 > r2 || t1 > b2 || r1 < l2 || b1 < t2) {
return false;
}
return true;
}
//矩形碰撞检测函数
function hitFunC(obj1,obj2){
//计算半径
var r1 = obj1.offsetWidth/2;
var r2 = obj2.offsetWidth/2;
//两个圆心之间的距离
var x1 = obj1.offsetLeft + r1;
var y1 = obj1.offsetTop + r1;
var x2 = obj2.offsetLeft + r2;
var y2 = obj2.offsetTop + r2; var dis = Math.sqrt(Math.pow((x1 - x2),2)+Math.pow((y1 - y2),2));//Math.pow() 求几次方 Math.sqrt 开方
//如果两个圆的圆心距离小于等于半径之和 证明两个圆有相交
if(dis <= r1+r2){
return true;
}
return false;
}
//检测圆形碰撞