我正在製作一款迷你遊戲,似乎無法讓我的玩家在綠色廣場上移動,但無法穿過它。當我嘗試使用當前的代碼時,角色可以在其附近移動,但不能通過綠色方塊的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>
也許看看這個答案關於二維形狀[在html5畫布中的碰撞檢測](http://stackoverflow.com/a/20887488/648350) – haxxxton