检测某些条件是否为真,如果是真,则执行进一步的操作

时间:2018-05-27 17:57:08

标签: javascript html

我正在为一个类制作一个游戏,我正在尝试创建一个函数来检测游戏的主要英雄是否在该方法定义的范围内,然后它将检查一系列if并执行它们如果在他们变得真实的任何一点。

initHitbox(hero,100,200,300,400);

function initHitbox(object1, leftBound, rightBound, topBound, botBound){
    //left boundary
    if(object1.y > topBound &&
       object1.y < botBound &&
       object1.x > leftBound &&
       object1.x < rightBound){
           console.log("YOU ARE IN THE BOX");
           if(object1.x < leftBound){
               object1.x = leftBound;
           }
           if(object1.x > rightBound){
               object1.x = rightBound;
           }
           if(object1.y > botBound){
               object1.y = botBound;
           }
           if(object1.y < topBound){
               object1.y = topBound;
           }
       }
    else{
        console.log("YOU ARE NOT IN THE BOX");
        null;
    }
}

在上面的代码中,它总是可以检测画布中的主要英雄角色是否在我使用控制台日志定义的参数范围内(始终显示“你不在盒子里”或“你在盒子里” “),但该方法不会在其下执行任何操作。

TLDR:希望对象被困在框中,不会被困在框中,但会在框中被检测到。

1 个答案:

答案 0 :(得分:0)

这个问题有点不清楚,但我猜你希望你的玩家被限制在指定的盒子里。如果玩家在盒子外面,你想“重置”玩家并将它们放回盒子里?

如果是这种情况,那么只需将4个if语句移动到else块:

initHitbox(hero,100,200,300,400);

function initHitbox(object1, leftBound, rightBound, topBound, botBound){
    //left boundary
    if(object1.y > topBound && object1.y < botBound && object1.x > leftBound && object1.x < rightBound){
	   console.log("YOU ARE IN THE BOX");
	}
    else{
        console.log("YOU ARE NOT IN THE BOX");
		
		// Move player back into the box by reseting the player's position
		if(object1.x < leftBound){
		   object1.x = leftBound;
		}
		if(object1.x > rightBound){
		   object1.x = rightBound;
		}
		if(object1.y > botBound){
		   object1.y = botBound;
		}
		if(object1.y < topBound){
		   object1.y = topBound;
		}
    }
}