2016-07-25 140 views
0

我基本上在畫布上做了兩面牆。一個在頂部,另一個在底部。我的球員由MOUSE控制,我想知道如何讓球員不能穿過牆壁。在畫布中碰撞檢測後停止玩家運動

下面是兩個物體之間的碰撞一般的功能:

function collides(a, b) { 
    var val = false; 

    val = (a.x < b.x + b.width) && 
    (a.x + a.width > b.x) && 
    (a.y < b.y + b.height) && 
    (a.y + a.height > b.y); 

    return val;   
} 

這裏的檢測碰撞檢測代碼:

if (collides(player, block)){ 
    //I don't know what goes here. 
} 

任何幫助,將不勝感激。

回答

0

重新定位球員,因爲你已經做了夾着球員的y位置始終在頂部和底部的牆壁之間。

在你的鼠標移動處理器(或任何玩家通過鼠標重新定位):

// reposition the player as you already do 
... 

// and clamp the player to stay below the top wall 
if(player.y < wall.y+wall.height){ player.y = wall.y+wall.height); 

// and clamp the player to stay above the bottom wall 
if(player.y+player.height > wall.y){ player.y = wall.y-player.height); 
+1

謝謝!我能夠得到它的工作。 –