Hello Everyone, I’m having trouble with this code, I have to edit a game. The question is…
In checkHit() function, use an array to store two distances, dist1 and dist2. Then replace two if statements with a for loop or a while loop.

Thanks.

var checkHit = function () {
// This function hides/kills dog and terminates the current game if 1 or 2 hits the dog;
// calculate two distances between dog and text1, between dog and text2
var dist1 = Math.sqrt(Math.pow(prex[1]-prex[0], 2) + Math.pow(prey[1]-prey[0], 2));
var dist2 = Math.sqrt(Math.pow(prex[2]-prex[0], 2) + Math.pow(prey[2]-prey[0], 2));
// if any distance is less than 20, hide dog
if ( dist1 < 20 ) {
dog.style.visibility = "hidden";
object1.style.visibility = "hidden";
alert("The dog was hit by digit 1!");
clearInterval(timeIntervalID);
}
if ( dist2 < 20 ) {
dog.style.visibility = "hidden";
object2.style.visibility = "hidden";
alert("The dog was hit by digit 2!");
clearInterval(timeIntervalID);
}

I’m not really sure what the question means? Currently, it’s more efficient to use your if statements (actually, a function would be better) than a loop since your objects aren’t arrays. You’ll just end up with a loop with two if statements anyways.

In other words, you’ll need to still use a conditional to determine if you need to update object1 vs object2 (and digite 1 vs digit 2), whereas if they were arrays you could loop through them as object[#]

var checkHit = function () {
var dist = 0;
for(var i = 1; i < 3; i++){
dist = Math.sqrt(Math.pow(prex[i]-prex[0], 2) + Math.pow(prey[i]-prey[0], 2))
if(dist < 20){
dog.style.visibility = "hidden"
window["object" + i].style.visibility = 'hidden' // Since this is a global variable, access it by name
alert('The dog was hit by digit ' + i + '!')
clearInterval(timeIntervalID)
}
}
};

With this setup, you can check against any number of objects (not just 2), by allowing the function to accept an argument objectCount:

var checkHit = function (objectCount) {
if(typeof objectCount === 'undefined')
objectCount = 2
var dist = 0;
for(var i = 1; i < objectCount + 1; i++){
dist = Math.sqrt(Math.pow(prex[i]-prex[0], 2) + Math.pow(prey[i]-prey[0], 2))
if(dist < 20){
dog.style.visibility = "hidden"
window["object" + i].style.visibility = 'hidden' // Since this is a global variable, access it by name
alert('The dog was hit by digit ' + i + '!')
clearInterval(timeIntervalID)
}
}
};