distanceTo(javaScipt)


#1

keeps saying i have to find where enemy is
here’s the code
loop {
var enemy = this.findNearestEnemy();
this.moveXY(21, 69);
if(this.distanceTo(enemy)<10){
if(this.isReady(“cleave”)){
this.cleave(enemy);
}
else{
this.attack(enemy);
}
}
else{
this.shield();

}

}


#2

What exactly are you trying to accomplish with this code? btw. read the sticky about code formatting put ``` on a line by itself before and after your code.

The code as you’ve shown will move to that static location, then if the enemy happens to be < 10 distance from you will either cleave or attack the enemy. otherwise it will stand there with shield up. That’s pretty much it. it won’t go after the enemy unless it gets close to you.


#3

also which level are you doing to ne specific


#4

The specific error you are dealing with is that you are telling him to find the distanceTo an enemy without making sure an enemy exists.


#5

the level is siege of stonehold


#6

To follow up, you need to check if you have found an enemy first. You can either “nest” (put one if check inside of the other) or use and “AND” check which in Javascript is the && operator. Here are the two examples to solve that one problem:

if (enemy) {
    if (this.distanceTo(enemy) < 10) {
    }
}

or

if (enemy && this.distanceTo(enemy) < 10) {
}

#7

Go back and do Patrol Buster first, use what you learned there in this one.