unity3d - How can I fix my chasing/attacking code? -


so how code works is, enemy find player , move towards him. when finds him, stop , start attacking. if player moves away though, enemy stop attacking , sit there until player comes range. how can fix when player moves out of range, enemy starts chasing again , attacks normal?

float movespeed = 3f; float rotationspeed = 3f; float attackthreshold = 3f;   //distance within attack float chasethreshold = 10f;   //distance within start chasing float giveupthreshold = 20f;  //distance beyond ai gives float attackrepeattime = 1f;  //time between attacks bool attacking = false; bool chasing = false; float attacktime; transform target;             //the enemy's target transform mytransform;        //current transform data of enemy  void update() {      //rotate @ player      float distance = (target.position - mytransform.position).magnitude;      if (chasing)      {          mytransform.rotation = quaternion.slerp(mytransform.rotation, quaternion.lookrotation(target.position - mytransform.position), rotationspeed * time.deltatime);      }       //move towards player      if (chasing == true && attacking == false)          mytransform.position += mytransform.forward * movespeed * time.deltatime;       //give if far away      if (distance >= giveupthreshold)      {          chasing = false;      //    attacking = false;      }       //attack, if close enough, , if time ok      if (distance <= attackthreshold && time.time >= attacktime) //if attacking want stop moving      {          //attack here          bossattack.attack();          attacktime = time.time + attackrepeattime;          print("attacking!");          attacking = true;        //  anim.settrigger("autoattack");          chasing = false;      }      else      {          //not chasing.          //start chasing if target comes close enough          if (distance <= chasethreshold)  //if gets chase, , move out of range again, won't chase again. attack if comes range again          {              chasing = true;            //  attacking = false;              //   print("chasing!");          }      }  } 

i think that's necessary relevant code.

the statement if (chasing == true && attacking == false) means both chasing must true, , attacking must false, attacking never gets set false after attacks first time (you've commented out of attacking = false lines).


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -