好吧,所以我有一个程序,该程序可以绘制3个具有任意位置的幻影并绘制一个包“ sac.gif”,您可以使用键盘上的箭头键在400 x 400的画布上四处移动。我试图做到这一点,以便每当用户将包图像移到幻影图像上时,三个幻影图像之一便会消失,而另外两个幻影图像会停留在它们的位置并等待,直到包影图像悬停在它们上方并使它们消失。那是问题所在。。。我不太确定如何实现检查袋子和鬼影是否接触并去除鬼影的功能。 感谢所有帮助。
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="Jeu.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"
style="border-color: 'black'; border-width: 3px; border-style: solid">
</canvas>
<br>
<button type="button"onclick="reset()"><img src="start.jpg"></button>
<script type="text/javascript">
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
window.onload = function() {
var canvas = document.getElementById("canvas");
var contexte = canvas.getContext("2d");
var T_fleche_gauche = 37;
var T_fleche_droite = 39;
var T_fleche_haut = 38;
var T_fleche_bas = 40;
var player = {
img: new Image();
};
var x = 100;
var y = 100;"
var w = 64;
var h = 64;
var dx = 0;
var dy = 0;
player.img.src = "sac.gif"
document.onkeydown = function(e) {
toucheCourante = e.keyCode;
if (toucheCourante == T_fleche_gauche) {
dx = -1;
dy = 0;
}
if (toucheCourante == T_fleche_droite) {
dx = 1;
dy = 0;
}
if (toucheCourante == T_fleche_haut) {
dy = -1;
dx = 0;
}
if (toucheCourante == T_fleche_bas) {
dy = 1;
dx = 0;
}
}
function dessiner(x, y) {
var random = function() {
return {
x: w + (Math.random() * (400 - (2*w))),
y: h + (Math.random() * (400 - (2*h)))
}
};
var points = [];
for (var i = 0; i < x; i++) {
points.push( random() );
}
return points;
};
var ghost = {
img: new Image(),
};
ghost.img.src = "ghost.png";
function affiche(x,y) {
for (var u of ghost.list) {
contexte.drawImage(ghost.img, u.x, u.y, 50, 60);
}
}
ghost.list = dessiner(3, ghost);
function draw() {
contexte.save();
contexte.clearRect(0, 0, 400, 400);
contexte.translate(10+2*x,10+2*y);
contexte.drawImage(player.img, x,y,70,90);
contexte.restore();
x = x+dx;
y = y+dy;
if (x > 125) x = -25;
if (x < -25) x = 125;
if (y > 125) y = -25;
if (y < -25) y = 125;
affiche();
window.requestAnimFrame(function() {draw(dx,dy)});
};
draw(1,0);
};
function reset(){
location.reload()
}
</script>
</body>
</html>
答案 0 :(得分:1)
首先,您需要实现一个函数来确定两个对象是否发生碰撞,并提供它们的x
和y
坐标以及它们的width
和height
。
像这样:function collide(o1, o2) {...} // returns true if they are colliding, false otherwise
。要编写此功能,您可能会发现它很有用:https://developer.mozilla.org/en-US/docs/Games/Techniques/2D_collision_detection
然后,您需要在update()
函数中为应该发生碰撞的每个对象调用它(我怀疑不是彼此之间的重影)。每次更新游戏状态(物体位置等)并重绘时,您都需要检查物体是否碰撞。
然后,如果检测到碰撞,则需要采取一些措施:生命下降,爆炸,游戏结束...
我没有设法使您的jsfiddle工作,因此我使用了上次制作的jsfiddle并对其进行了更新:https://jsfiddle.net/nmerinian/t0c3sh8f/36/
编辑:我忘了让幽灵消失。为了简化一切,我创建了Bag
和Ghost
对象:https://jsfiddle.net/nmerinian/t0c3sh8f/56/