我试图在javascript中编写类似于as3.0的命中测试的函数。 我将圆圈放在div标签中定义的屏幕上,然后我遍历所有圆圈以查看它们的位置是否重叠。
html文件中的内容:
<div class="balls">
<script>
for (i=0;i<10;i++){
document.write("<div id='ball"+i+"' class='ball'></div>");
}
</script>
</div>
使用jquery放置它们:
var amount = 10;
var height = 270;
var width = 450;
function setBalls(){
for (i=0;i<amount;i++){
$("#ball"+i).css('top',parseInt(Math.random()*height)+'px');
$("#ball"+i).css('left',parseInt(Math.random()*width)+'px');
for (j=0;j<i;j++){
hitTest($("#ball"+i),$("#ball"+j));
}
}
}
上面调用的hitTest函数:
function hitTest(object1,object2){
var left1 = parseInt(object1.css('left'));
var left2 = parseInt(object2.css('left'));
var top1 = parseInt(object1.css('top'));
var top2 = parseInt(object2.css('top'));
var width1 = parseInt(object1.width());
var width2 = parseInt(object2.width());
var height1 = parseInt(object1.height());
var height2 = parseInt(object2.height());
var horTest = false;
var verTest = false;
if (((left1 >= left2)&&(left1 <= left2 + width2))||((left2 >= left1)&&(left2 <= left1 + width1))){
horTest = true;
}
if (((top1 >= top2)&&(top1 <= top2 + height2))||((top2 >= top1)&&(top2 <= top1 + height1))){
verTest = true;
}
if(horTest&&verTest){
console.log("hit");
object1.css('top',parseInt(Math.random()*height)+'px');
object1.css('left',parseInt(Math.random()*width)+'px');
hitTest(object1,object2);
}
}
样式表信息:
.ball{
width:50px;
height:50px;
background:green;
border-radius:100%;
position:absolute;
}
.balls{
width:500px;
height:320px;
background:red;
position:absolute;
left:10px;
top:80px;
}
任何人都可以详细说明为什么这样做?
提前致谢
更新:我的算法肯定存在错误。我现在尝试了20个“球”,现在每次都打破了
答案 0 :(得分:0)
我发现了错误。在我的hitTest中,在我重新定位元素之后,我只测试第二个元素,而不是再次针对所有元素。新功能现在100%工作:
放球:
function setBalls(){
for (i=0;i<amount;i++){
$("#ball"+i).css('top',parseInt(Math.random()*height)+'px');
$("#ball"+i).css('left',parseInt(Math.random()*width)+'px');
for (j=0;j<i;j++){
hitTest($("#ball"+i),$("#ball"+j),j);
}
}
}
hitTest函数:
function hitTest(object1,object2,prevBalls){
var left1 = parseInt(object1.css('left'));
var left2 = parseInt(object2.css('left'));
var top1 = parseInt(object1.css('top'));
var top2 = parseInt(object2.css('top'));
var width1 = parseInt(object1.width());
var width2 = parseInt(object2.width());
var height1 = parseInt(object1.height());
var height2 = parseInt(object2.height());
var horTest = false;
var verTest = false;
if (((left1 >= left2)&&(left1 <= left2 + width2))||((left2 >= left1)&&(left2 <= left1 + width1))){
horTest = true;
}
if (((top1 >= top2)&&(top1 <= top2 + height2))||((top2 >= top1)&&(top2 <= top1 + height1))){
verTest = true;
}
if(horTest&&verTest){
console.log("hit");
object1.css('top',parseInt(Math.random()*height)+'px');
object1.css('left',parseInt(Math.random()*width)+'px');
for (j=0;j<prevBalls;j++){
hitTest(object1,$("#ball"+j),j);
}
hitTest(object1,object2);
}
}