2015-09-04 70 views
0

我正試圖在畫布中開發迷宮遊戲。我手工繪製了迷宮,如檢查畫布中迷宮遊戲的碰撞

context.moveTo(100,700); 
    context.lineTo(100,600); 
    context.lineTo(200,600); 
    context.lineTo(200,500); 

還有更多。我想通過這些線移動物體而不移過這些邊界。

爲此,我曾嘗試下面的代碼:

function right() { 
    context.clearRect(0, 0, canvas.width, canvas.height); 

    art(); 
    myImage11.src = "Point.png"; 
    x += 20; 

    if ((x + 20 < 50)) { 
     context.clearRect(0, 0, canvas.width, canvas.height); 
     checkcollision(); 
     if (collision == 1) { 
      x -= 20; 
      collision = 0; 
     } 

     context.drawImage(myImage11, x, y, 50, 50); 
    } 

我checkcollision功能確實

function checkcollision() { 
    var myImage11 = context.getImageData(x, y, 10, 10); 
    var pix = myImage11.data; 
    for (var i = 0; n = pix.length, i < n; i += 4) { 
     if (pix[i] == 0) { 
      collision = 1; 
     } 
    } 
} 

但它不工作。請幫忙解決這個問題! 在此先感謝

+0

什麼是你的'checkcollision'功能嗎? – nils

+0

函數checkcollision(){ \t \t \t var myImage11 = context.getImageData(x,y,50,50); \t \t \t var pix = myImage11.data; \t \t \t爲(VAR I = 0; N = pix.length,I Andrew

+0

每個像素應該是陣列中的4(RGBA)條目(所以10×10 = 400 ARRAYSIZE),http://www.w3schools.com/tags/tryit.asp? filename = tryhtml5_canvas_getimagedata2 – dwana

回答

0

這是難以推斷當前場景的精確運作,如碰撞僅選中時x + 20 < 50,但問題可能是從中獲得getImageData面積:x和的y位置'avatar',寬度爲10(context.getImageData(x, y, 10, 10);)這將檢查newavatar位置的左側是否有碰撞,但不是右側移動的方向。爲此,應該檢查x + avatarWidth- XMovement和XMovement的寬度。

也許與您當前的設置不完全相符,但是製作了模擬運動的fiddle。在其中,整個化身目標位置被檢查以進行更快速的設置,但是如果需要的話可以被優化以使用新的重疊。

var canvas = document.getElementById('canvas'); 
var context = canvas.getContext('2d'); 
var x = 100, y = 200; 
var imgWidth = 50, imgHeight = 50; 

var checkcollision = function(){ //checks collision of the entire 'avatar' rectangle. This can be done more efficiently by only checking the moved to area, but that would require different parameters per direction. 
    var data = context.getImageData(x , y, imgWidth, imgHeight).data; 
    return data.some(function(p){ return p != 0;}); 
} 

function right() { 
    context.clearRect(0,0, canvas.width, canvas.height); 

    art(); //draw maze 
    //myImage11.src = "Point.png"; 

    var curx= x; 
    x+=20; 

    while(checkcollision() && x > curx){ //while collision decrease x (note, this could be more efficient by just checking the new position overlap) 
     x--; 
    } 

    drawAvatar(); 
} 


function art(){ 
    context.moveTo(100,400); //decreased y a bit to keep it easier viewable while testing 
    context.lineTo(100,300); 
    context.lineTo(200,300); 
    context.lineTo(200,200); 
    context.stroke(); 
} 

function drawAvatar(){ 
    //context.drawImage(myImage11, x, y, imgWidth, imgHeight); 
    context.fillRect(x,y,imgWidth,imgHeight); 
} 

art();drawAvatar(); 
0

圖像數據都做了一些奇怪的東西 有時你畫的顏色是關閉了一點。 檢查Y = 98,99,100 http://jsfiddle.net/15wsszw4/

公式得到x處像素的紅色值差異性之探源,Y

console.log('R:'+imgData.data[y*4*c.width+x*4])