2013-08-27 63 views
1

我在HTML5 +帆布新我找不到關於我的問題的詳細信息,我決定在這裏問滾動...帆布帶衝突檢測

我需要滾動大地圖的幫助 - 2800x1500px在畫布400x300px,並在畫布外的「不可見區域」進行碰撞檢測。

這樣的:
http://i.stack.imgur.com/NI59z.png

從我的代碼一些功能

function Map() 
{ 
    this.img = new Image(); 
    this.img.src = "img/map.jpg"; //map picture on main canvas 
    this.gimg = new Image(); 

    //map with opacity on "ghost" canvas for collision detecting 
    this.gimg.src = "img/gmap.png"; 
    this.draw = function(ctx,gctx) 
    { 
     ctx.drawImage(this.img,-offset.x,-offset.y);  
     gctx.drawImage(this.gimg,-offset.x,-offset.y); 
    } 
} 
function init() 
{ 
    var gameLoop = setInterval(function() { 
     draw(ctx,gctx); 

    }, 1000/fps); 
} 
function draw(ctx,gctx) 
{ 
    ctx.save(); 
    gctx.save(); 
    ctx.clearRect(-offset.x,-offset.y,2800,1500); 
    gctx.clearRect(-offset.x,-offset.y,2800,1500); 
    map.draw(ctx,gctx); 
    ctx.translate(offset.x,offset.y); //scrolling canvas 
    gctx.translate(offset.x,offset.y); //scrolling ghost canvas 
    ctx.restore(); 
    gctx.restore(); 
} 

//collision detecting function 
function hitTest(obj,gctx) 
{ 
    var imageData = gctx.getImageData(obj.x,obj.y,1,1); 
    if(imageData.data[3]==255) 
    { 
     return true; 
    } 
    else return false; 
} 

滾動地圖我使用例如:

我的項目:
http://game.com.hostinghood.com/

回答

0

你不能用不在可視區域中的物體進行碰撞。該圖像沒有被渲染到該部分的畫布上,因此它總是具有0不透明度。

有兩種方法可以做到這一點。一種方法是在單獨的內存畫布上渲染碰撞圖,該畫布與碰撞圖的寬度和高度相同,然後將活動活動畫布上敵人的座標與碰撞圖上的區域進行比較。這可能是您查看代碼後最簡單的方法。

第二種方法是使用瓷磚地圖。你基本上有一個2d數組,其中每個元素代表一個區域可以說32x32,如果它的a 1可以碰撞,如果它的a可以通過。這將涉及將敵人位置轉換到陣列上的區域進行檢查。

我已經完成了這兩種方式,在內存利用率方面最好的是tilemap方法。

Here is a great tutorial explaining the tilemap approach