Hi so i have gotten stuck at trying to make my code to run a certain number of times in a row before exiting.
// findTree(); is another function
var tree = findTree();
//if we can’t find a tree.
if (tree === false){
rotateCamera();
continue;
}
im trying to make so the Camera rotates only 5times in a row and if it doesnt find any tree it will exit the code. if it do find a tree it will countinue until it doesn’t find a tree 5 camera rotatetions before it stops the code.
So currently your code seems to be checking for the presence of a tree once, and if it doesn’t find one rotates the camera once.
We can use a simple for loop to make the camera rotate no more than 5 times if tree is initially false. Even better, put that for loop in a function that you can call to do the camera rotations and check for a tree at any point in your code.
Here’s one way you can do that:
var tree = findTree();
var searchForTree = () => {
rotateCamera(); // rotate once here
for (let i = 0; i < 4; i++) {
tree = findTree();
// if we find a tree we exit both the loop and searchForTree function
// and return true indicating a tree was found
if (tree) {
return true
}
// Otherwise rotate the camera until we find a tree
rotateCamera();
}
// If code reaches here, it means we exited the loop after rotating 5 times and have not found a tree
// so we return false
return false
}
//if we can’t find a tree.
if (tree === false) {
var isThereATreeInSight = searchForTree() // this will be false if no tree was found after 5 rotations
// If there was not tree found stop your code
if (!isThereATreeInSight) {
// ... exit the calling function or throw an error
throw new Error('No tree was found')
}
}
// continue your code execution