2014-12-13 28 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