话不多少,直接上效果图。
贴代码
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>碰撞检测</title>
<style>
html,body{
margin:0;
padding:0;
height:100%;
}
#movele{
position: absolute;
top:0;
left:0;
height:150px;
width:150px;
background-color:red;
border-radius: 50%;
color:#fff;
text-align: center;
}
</style>
</head>
<body>
<div id="movele"><br/><br/><br/>假设这是张图片</div>
</body>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
(function(){
var elementMove=function(option){
this.container=option.container;
this.element=option.element;
this.speed = {};
if(option.speed){
if(typeof option.speed=="object"){
this.speed.x = option.speed.x;
this.speed.y = option.speed.y;
}
else{
this.speed.x = option.speed;
this.speed.y = option.speed;
}
}
else{
this.speed.x = 2;
this.speed.y = 2;
}
this.pos={
"left":0,
"top":0
};
this.xdir = 1;
this.ydir = 1;
this.Animation();
};
elementMove.prototype={
move:function(){
this.getPos();
$(this.element).css({
"left":this.pos.left,
"top":this.pos.top
})
this.Animation();
},
getPos:function(){
var jqConTainer = $(this.container);
var jqEle = $(this.element);
var offset = jqEle.offset();
//碰撞检测start
if(offset.left <= 0){
this.xdir = 1;
}
else if(offset.left+jqEle.width() >= jqConTainer.width()){
this.xdir = -1;
};
if(offset.top <= 0){
this.ydir = 1;
}
else if(offset.top +jqEle.height() >= jqConTainer.height()){
this.ydir = -1;
};
//碰撞检测end
this.pos.left = this.pos.left + this.xdir * this.speed.x;
this.pos.top = this.pos.top + this.ydir * this.speed.y;
},
Animation:function(){
var that=this;
requestAnimationFrame(function(){
that.move();
})
},
};
//实例化
var mymoveInstance = new elementMove({
"element" :"#movele",
"container" :"body",
"speed":{
"x":6,
"y":5
}
});
})();
</script>
</html>
这是@懵萌酱 提问的,纯手打一份代码,欢迎交流。
提问原文