0
即时尝试做一个游戏,在主角和对手之间发生碰撞。我不能得到碰撞工作,虽然,我一直在使用,则x和y位置的x和y位置加上宽度和主角的高度和拮抗剂试图检测画布上的碰撞
var canvas = document.getElementById('canvas');
var PX = 10;
var PY = 10;
var PW = 10;
var PH = 10;
var P = PX + PY;
var EX1 = 100;
var EY1 = 100;
var EW1 = 10;
var EH1 = 10;
var E1 = EX1 + EY1;
window.addEventListener("keydown", charMove);
window.addEventListener("keyup", charMove);
window.addEventListener("keypress", charMove);
window.onload = function() {
context = canvas.getContext("2d");
canvas.style.background = "black";
var framesPerSecond = 30;
setInterval(function() {
\t draw();
\t move();
}, 1000/framesPerSecond);
}
function draw() {
\t //EX context.fillRect(PosX, PosY, width, height);
\t //draws protagonist
\t context.beginPath();
\t context.clearRect(0, 0, canvas.width, canvas.height);
\t context.fillStyle = "blue"
\t context.fillRect(PX, PY, PW, PH);
\t context.stroke();
\t context.closePath();
\t //draws antagonist(s)
\t context.beginPath();
\t context.fillStlyle = "red";
\t context.fillRect(EX1, EY1, EW1, EH1);
\t context.stroke();
\t context.closePath();
}
function move() {
}
function charMove(){
\t var x = event.which || event.keyCode;
\t if(x == 37){
\t \t PX -= 1;
\t }
\t if(x == 38){
\t \t PY -= 1;
\t }
\t if(x == 39){
\t \t PX += 1; \t
\t }
\t if(x == 40){
\t \t PY += 1;
\t }
}
//detect collision
setInterval(function() {
\t if(PX > EX1 || PX + PW < EX1 + EW1 && PY + PH > EY1 + EH1 || PY + PH < EY1 + EH1){
\t \t window.alert("collision");
\t }
}, 1);
<html>
<head>
</head>
<body>
<canvas width="500px" height="500px" id="canvas" class="canvas">
</body>
</html>
你有喜欢的网页,可以帮助我的任何示例代码。我更关注学习者。 –
我写的代码应该和你一起工作。如果您无法理解它,请尝试在纸上画出一维和二维的碰撞。 – Joonazan
好吧,谢谢你,圣诞快乐! –