the game i'm making has character , enemy. when character gets hit closes health. if character can avoid getting hit 10 seconds regains 5 points of health. if 10 seconds pass , still not hit gains 5 points , keeps on happening until character regains full health. if character hits before 10 seconds completed loses health , time starts over.
currently when run c# script except keep giving health player. if hit records time. 10 seconds pass , gives me health after update
function not continue give me health once. think logic somewhere not correct. guys think ??
public slider healthbar; public float hitresettimer; //resetsthetimerto0whenihavebeenhitwithinthe10seconds; bool beenhit; //return true or false if ihave been hit float hittimer; //keeps track of time 0 10 if have not been hit void awake() { beenhit=false; //player has not been hit so= false hittimer=0.0f; //set 0 because have not been hit yet no time needs registered } void ontriggerenter(collider other) { healthbar.value-=10;//if enemy hits character loses 10 points beenhit= true; //is set true because have been hit hittimer= hitresettimer;//if cube hits hittimer no longer time has occured reset 0 } void restorehealth() { if(!beenhit&& healthbar.value<100) healthbar.value+=2; } //usethisfor initialization void start () { } //updateiscalledonceper frame void update () { if(beenhit) { hittimer -=time.deltatime; if(hittimer<0) { beenhit = false; restorehealth(); } } }
in update
method:
if(hittimer<0) { beenhit = false; restorehealth(); }
take restorehealth();
out of if
s.
void update () { if(beenhit) { hittimer -=time.deltatime; if(hittimer<0) { beenhit = false; } } restorehealth(); }
the point check beenhit
in order reduce hittimer
. once hittimer < 0
set beenhit = false
, restorehealth();
. after have beenhit = false
, update
method having inside if(beenhit)
gets false
state always. code never reaches restorehealth();
until set beenhit = true
in ontriggerenter()
in turn resets timer , wait again 10 seconds.
what checking time difference between current time , time character got last hit.
float lasthit; // holds last time character got hit void awake() { lasthit = time.time; } void ontriggerenter(collider other) { healthbar.value -= 100;//if enemy hits character loses 10 points lasthit = time.time; } void restorehealth() { if(healthbar.value<100) healthbar.value+=2; } //updateiscalledonceper frame void update () { if (time.time - lasthit > 10) // 10 seconds { restorehealth(); } }
note: should change restorehealth()
method give health specific delay (say 1 second) not on every frame. since update
call every frame after matching conditions.
Comments
Post a Comment