Reputation: 323
I have an array of platforms that I'm hitTesting against a player. I also have a boolean variable called onGround that is attached to the player.
I need to be able to toggle onGround based on whether or not the player is hitting a platform in the array. It's been easy to check if the player is hitting a platform with:
//loop through array
var platform = platformArray[i];
if(player.hitTestObject(platform)){ onGround = true;}
Unfortunately, checking if the player is not hitting a platform has caused a lot of confusion. Even with:
if(!player.hitTestObject(platform)){ onGround = false;}
because of logic, if the player would be touching a platform, it would also not be touching another platform and the above line would still execute. onGround will continually swap between true and false.
I need to be able to check if all of the platforms in the array are not being hit at the same time. Dozens of my own solutions have mostly failed me. Is the player hitting at least 1 platform in the array, or none at all? Any ideas?
Upvotes: 0
Views: 107
Reputation: 46037
Your first method is sufficient. You only need to check whether onGround
is false after the loop, i.e. after testing against all platforms.
// set initial value of onGround to false
onGround = false;
//loop through array
var platform = platformArray[i];
if (player.hitTestObject(platform)) {
onGround = true;
break;
}
// after loop
if (onGround) {
// at least one is hit
} else {
// none is hit
}
A better approach will be to wrap the logic inside a function. Something like this:
function isAnyPlatformHit(platformArray, player):Boolean {
for (var i:int = 0; i < platformArray.length; i++) {
var platform = platformArray[i];
if (player.hitTestObject(platform)) {
return true;
}
}
return false;
}
if (!isAnyPlatformHit(platformArray, player)) {
// none hit
}
Upvotes: 1