我试图使用html、css、jquery和javascript制作一个相当简单的空间入侵者克隆。在我对子弹和敌人进行碰撞检测之前,一切都很顺利。我看了一会儿,但找不到任何能帮助我的东西,因为我没有使用画布。我该怎么做?
这是Javascript:
function init() {
$("#playerShip").hide();
$("#playerMarLeftCounter").hide();
$("#startButton").click(startGame);
}
function startGame() {
$("#playerShip").show();
$("#title").hide();
$("#startButton").hide();
}
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
{keycode = window.event.keyCode;}
else if (e)
{keycode = e.which;}
if(keycode == 37){
playerMoveLeft();
}
else if (keycode == 39){
playerMoveRight();
}
else if (keycode == 32){
shipFireBullet();
}
//alert("keycode: " + keycode);
}
function shipFireBullet(){
$("#shipBullet").css("animation-name", "fireBullet");
setTimeout(function(){ $("#shipBullet").css("animation-name", "nothing"); }, 750);
}
function playerMoveLeft(){
var whatMarLeft = $("#playerMarLeftCounter").html();
whatMarLeft = parseInt(whatMarLeft);
if (whatMarLeft <= -160){
return false;
}
else{
//alert (whatMarLeft);
var x = whatMarLeft - 15;
//alert(x);
$("#playerShip").css("margin-left", x);
$("#playerMarLeftCounter").html(x);
}
}
function playerMoveRight(){
var whatMarLeft = $("#playerMarLeftCounter").html();
whatMarLeft = parseInt(whatMarLeft);
if (whatMarLeft >= 1080){
return false;
}
else {
//alert (whatMarLeft);
var x = whatMarLeft + 15;
//alert(x);
$("#playerShip").css("margin-left", x);
$("#playerMarLeftCounter").html(x);
}
}
我知道这可能有点麻烦,因为我刚开始编程,但如果有人能帮我降低碰撞检测,那就太好了。谢谢
不确定JQuery。但是在普通JS中,您可以在HtmlElement
上使用getBoundingClientRect()
来获取它的位置和大小。它将返回一个属性为{top, left, bottom, right, width, height}
的对象。从那时起,你可以使用简单的矩形相交测试来查看元素是否相互接触/相交,如下所示:
// if colliding - will return true
function areColliding(r1, r2) {
if (r1.left >= r2.right || r1.right >= r2.left)
return false;
if (r1.top <= r2.bottom || r1.bottom <= r2.top)
return false;
return true;
}
剩下的只是在对象中循环,用getBoundingClientRect()
获取它们的rect,并检查它们是否与areColliding()
冲突。
p.s。我会使用position: absolute
和transform: translate(X, Y);
来设置元素的位置。这样,如果你知道尺寸,你就不需要每次都调用getBoundingClientRect()
——这是一个非常昂贵的操作。