2017-04-20 57 views
-2

在javascript中,我制作了一个HTML画布游戏,在那个游戏中我有一个名为gamePiece的对象类型/构造函数。游戏币有一个功能叫做checkCollision:为什么我的情况不起作用?

this.checkCollision = function(piece){ 
    var collisionX = piece.x >= this.x && piece.x <= (this.x + this.width); 
    var collisionY = piece.y <= this.y && piece.y <= (this.y - this.height); 
    if(collisionX || collisionY){ 
     return true; 
    } else { 
     return false; 
    } 
} 

这是由更新称为()

function update(){ 
context.clearRect(0, 0, game.width, game.height); 
for(var i = 0; i < gamePieces.length; i++){ 
    gamePieces[i].update(); 
    for(var mi = 0; mi < gamePieces.length; mi++){ 
     gamePieces[i].checkCollision(gamePieces[mi]); 
     if(gamePieces[i].checkCollision(gamePieces[mi]) == true){ 
      gamePieces[i].collisionFunction(); 
     } 
    } 
} 
} 
setInterval(function(){update();}, 1); 

我有一个应该在与其他游戏人物碰撞给提升速度的另一个对象,它记录每次都会提高速度。

var speedBooster = new gamePiece(25,25,"red",300,300,0); 
speedBooster.collisionFunction = function(){ 
    for(var whichpiece = 0; whichpiece < gamePieces.length; whichpiece++){ 
     if(speedBooster.checkCollision(gamePieces[whichpiece]) == true && gamePieces[whichpiece] != this){ 
      gamePieces[whichpiece].speed += 10; 
      console.log("gamePieces[" + whichpiece + "] has been given a speed boost."); 
     } 
    } 
} 

但是它给出了一个速度提升,只要一块是它的背后,我把“piece.x> = this.x & &”有原因的。为什么JavaScript忽略了我给它的条件?

+0

'x'和'y'是否跟踪物体中心的坐标?如果是这样,问题可能是你正在使用x和y的对象的全部宽度,分别在正面和负面方向,而不是集中在对象上。即是否会像这样工作? var collisionX = piece.x> =(this.x - this.width/2)&& piece.x <=(this.x + this.width/2); var collisionY = piece.y <=(this.y - this.height/2)&& piece.y <=(this.y + this.height/2); 另外,你应该在(this.y - this.height)中使用'+'。 –

+0

谢谢,但仍然产生鬼碰撞 – C12

回答

0

尝试

var collisionX = piece.x >= this.x && piece.x <= (this.x + this.width); 
var collisionY = piece.y >= this.y && piece.y <= (this.y + this.height); 
if(collisionX && collisionY){ 
    return true; 
} else { 
    return false; 
} 

为了测试两个对象重叠。如果物体有x,y作为左上角,w,h作为宽度和高度

//Returns true if any part of box1 touches box2 
function areaTouching(box1,box2){ 
    return ! (box1.x > box2.x + box2.w || 
       box1.x + box1.w < box2.x || 
       box1.y > box2.y + box2.h || 
       box1.y + box1.h < box2.y) 
} 
+0

谢谢,但只考虑对象是否在对象的确切x点,我需要它发生时,对象的任何部分触摸 – C12

+0

@ C12已添加测试的例子if盒子重叠 – Blindman67

相关问题