简体   繁体   English

canvas xy坐标检测

[英]canvas x y coordinate detection

I am making a mini-game and cant seem to be able to get my player to move around the green square but not go through it. 我正在制作一个迷你游戏,似乎无法让我的玩家在绿色方块周围移动,但无法通过它。 When i try my current code the character can move near it but not got passed the x, y coordinates of the green square. 当我尝试当前的代码时,角色可以在其附近移动,但无法通过绿色方块的x,y坐标。 Please help 请帮忙

 <!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> 

What is your collision code intending to do? 您的碰撞代码打算做什么? when you move the character up you do px - 1 but when it meets the if condition you do px + 1. You are subtracting one and then adding one straight away. 当您将字符向上移动时,您执行px-1,但是当满足if条件时,您执行px +1。先减去一,然后立即相加一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM