Collsioin Detection of Javascript 2d Box



我正在尝试在周末使用 JavaScript 制作一个程序,该元素使黑盒在达到框的极限时,使用一系列if statement在屏幕上随机移动,我希望它向另一个随机方向反弹。

下面的代码制作了我上面描述的程序,但过了一会儿,当它撞到一侧时,盒子就会消失。我已经尽我所能,但问题仍然存在。值得注意的是,当它撞到右侧或底部时,它通常会消失。此外,盒子消失后会继续移动,(我通过扩展画布来解决这个问题)几乎就像if statement甚至不起作用一样。

代码:

<DOCTYPE. html>
<html>
<title>Moving Box</title>
<canvas id="myCanvas" width="1000" height="1000" style="border:1px solid #000000;"></canvas>
<script>
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var box = function(x,y){
this.x = x;
this.y = y;
var min = 0;
var max = 1000;

var corner = false;
var dirx;
var diry;
var corner; 
var rand = function(){
return Math.floor((Math.random() * 2) + 1);
}
var change = function(){
var choice = Math.floor((Math.random() * 2) + 1);
if(choice == 1){
  return -1;
}

if(choice == 2){
  return 1;
}
}
this.draw = function(){
  ctx.clearRect(0,0,1920,1080);
  ctx.fillRect(x,y,20,20);
  //tests corners
  if(x == min && y == min){
    dirx = rand();
    diry = rand();
    corner = true;
  } else if(x == max && y == max){
    dirx = rand() * -1;
    diry = rand() * -1;
    corner = true;
  } else if(x == max && y == min){
    dirx = rand() * -1;
    diry = rand();
    corner = true;
  } else if(x == min && y == max){
    dirx = rand();
    diry = rand() * -1;
    corner = true;
  } else {
    corner = false;
  }
  //tests sides
  if(y == min && corner == false){ //top side
    diry = rand();
    dirx = rand() * change();
  } else if(x == max && corner == false){ //right side
    dirx = rand() * -1;
    diry = rand() * change();
  } else if(y == max && corner == false){ //bottom side 
    diry = rand() * -1;
    dirx = rand();
  } else if(x == min && corner == false){ //left side
    dirx = rand();
    diry = rand() * change();
}

y = y + diry;
x = x + dirx;
}
}
Box = new box(0, 1000);
setInterval( function() {
Box.draw();
}, 1);
</script>
</html>

change()函数只是给出 +1 或 -1 来改变方向,使其看起来更随机。

在测试检查中检查大于(或小于)以及等于。不仅仅是顶部 == 分钟等。例如,做前>= 分钟

最新更新