为什么我的病情不起作用?

时间:2017-04-20 00:29:12

标签: javascript html canvas game-physics

在javascript中,我正在制作一个HTML画布游戏,在那个游戏中我有一个名为gamePiece的对象类型/构造函数。 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;
    }
}

由update()

调用
    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.");
        }
    }
}

但是只要一件作品落后于它,它就会提高速度,我把&#34; piece.x&gt; = this.x&amp;&amp;&#34;有一个原因。为什么JavaScript忽略了我给它的条件?

1 个答案:

答案 0 :(得分: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)
}
相关问题