我正在制作迷你游戏,似乎无法让我的玩家在绿色广场周围移动而不能通过它。当我尝试当前的代码时,角色可以在它附近移动,但没有通过绿色方块的x,y坐标。请帮忙
<!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(){
draw();
collision();
}, 1);
function draw(){
//clears junk
context.clearRect(0, 0, canvas.width, canvas.height);
//draws player
context.fillStyle = "red";
context.fillRect(px, py, pw, ph);
context.fill();
context.fillStyle = "green";
context.fillRect(ex, ey, ew, eh);
context.fill();
}
function collision(){
if(px < ex + ew && px + pw > ex){
px++;
}
if(py < ey + eh && ph + py > ey){
py++;
}
}
function moveChar(){
var k = event.which || event.keyCode;
if(k == 37){
px -= 1;
}
if(k == 38){
py -= 1;
}
if(k == 39){
px += 1;
}
if(k == 40){
py += 1;
}
}
</script>
</body>
</html>
&#13;
答案 0 :(得分:2)
你的碰撞代码是什么意思?当你移动角色时你做了px - 1但是当它遇到if条件你做px + 1.你正在减去一个然后直接加一个。