2014-12-13 33 views
0

我想用画布元素,使得在使用一系列if statement随机方向在屏幕周围的黑色框移动,当它击中框的限制,以使程序上周末在JavaScript ,我希望它能够以另一个方向反弹。Collsioin检测箱

下面的代码使得我上述程序,但经过一段时间它时,它经过一段时间击中侧的框会消失。我已经尽力了,但问题仍然存在。值得注意的是,它在击中右侧或底侧时通常会消失。此外,箱子消失后它会继续移动(我通过扩大画布计算出来),就好像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改变方向,使它看起来更加随意。

回答

1

除了等于在您的测试检查中检查是否大于(或小于)。不只是顶部==分等。做顶部> =分钟例如

+0

对于没有代码和废话语法...在移动。 – Todd 2014-12-13 17:23:22