2017-01-28 127 views
1

我正在製作一款迷你遊戲,似乎無法讓我的玩家在綠色廣場上移動,但無法穿過它。當我嘗試使用當前的代碼時,角色可以在其附近移動,但不能通過綠色方塊的x,y座標。請幫助畫布x座標檢測

<!DOCTYPE html> 
 
<html> 
 
    <style> 
 
    #canvas{ 
 
     background-color: black; 
 
    } 
 
    </style> 
 
<body> 
 
<canvas id="canvas" height="300px" width="300px"/> 
 
<script> 
 
var canvas = document.getElementById("canvas"); 
 
var context = canvas.getContext("2d"); 
 
var px = 100; 
 
var py = 100; 
 
var pw = 10; 
 
var ph = 10; 
 
var ex = 10; 
 
var ey = 10; 
 
var ew = 10; 
 
var eh = 10; 
 

 
window.addEventListener("keydown", moveChar); 
 
window.addEventListener("keyup", moveChar); 
 
window.addEventListener("keypress", moveChar); 
 

 

 
//frames update 
 
setInterval(function(){ 
 
\t draw(); 
 
\t collision(); 
 
}, 1); 
 
function draw(){ 
 
\t //clears junk 
 
\t context.clearRect(0, 0, canvas.width, canvas.height); 
 
\t //draws player 
 
\t context.fillStyle = "red"; 
 
\t context.fillRect(px, py, pw, ph); 
 
\t context.fill(); 
 
\t context.fillStyle = "green"; 
 
\t context.fillRect(ex, ey, ew, eh); 
 
\t context.fill(); 
 
} 
 
function collision(){ 
 
\t if(px < ex + ew && px + pw > ex){ 
 
\t \t px++; 
 
\t } 
 
\t if(py < ey + eh && ph + py > ey){ 
 
\t \t py++; 
 
\t } 
 
} 
 
function moveChar(){ 
 
\t var k = event.which || event.keyCode; 
 

 
\t if(k == 37){ 
 
\t \t px -= 1; 
 
\t } 
 
\t if(k == 38){ 
 
\t \t py -= 1; 
 
\t } 
 
\t if(k == 39){ 
 
\t \t px += 1; 
 
\t } 
 
\t if(k == 40){ 
 
\t \t py += 1; 
 
\t } 
 
} 
 
</script> 
 
</body> 
 
</html>

+0

也許看看這個答案關於二維形狀[在html5畫布中的碰撞檢測](http://stackoverflow.com/a/20887488/648350) – haxxxton

回答

2

什麼是你的碰撞代碼打算做什麼?當你移動角色時,你做px-1,但是當它滿足if條件時,你做px + 1.你正在減去一個,然後直接加一個。

+0

我想要紅色廣場在綠色廣場周圍移動,但不通過它。當我添加到px和py它檢測到兩者之間的碰撞,然後添加一個,所以它劑量通過綠色廣場。問題是我的if語句生成的不可見邊框。我無法弄清楚 –

+0

沒問題,所以我很快添加了一些功能,我相信,你想要什麼或者是它的一部分......將會有更多的案例需要討論,但這應該是一個起點。我嘗試將每一個步驟都提取爲具有長名稱的函數,以告訴您他們的工作。希望這可以幫助。 [jsbin link](https://jsbin.com/goraxeg/2/edit?html,js,output) – dandro