- Home /
PlayerHealth drops fast and wont reset
Need help with my player health. when the enemy collides with my player the health goes from 100 to 0 in 1 or 2 second. it drops fast and it will not reset the health back to 100. here are my java scripts. this is for a mobile game that i am working on.
PlayerHealth Script:
var enemyDead: boolean = false; static var playerHealth: float = 100; var LavaDeath: boolean = false; var enemy1: Rigidbody; var enemy2: Rigidbody; var prefab: Transform;
function Start(){ playerHealth = 100;
}
function Update(){
if(playerHealth <= 0){ Destroy(gameObject); Application.LoadLevel(2);
}
}
function OnGUI(){ GUI.Label(Rect(100, 100, 50, 50), "Player Health: " + playerHealth );
}
function OnControllerColliderHit(hit: ControllerColliderHit) {
if(hit.gameObject.tag == "Lever"){ hit.gameObject.animation.Play("PulledLever");
}
if(hit.collider.tag == "Floor"){ hit.collider.animation.Play("Cube"); print("Floor Trigger Active!!!"); }
if(hit.gameObject.tag == "enemy1" || hit.gameObject.tag == "enemy2"){
playerHealth -= 5;
}
if(hit.collider.tag == "LavaDeath"){
Destroy(gameObject, 2);
print("Im On Fire!!");
Application.LoadLevel(2); }
}
EnemyScript:
var thePlayer: GameObject; var enemyHealth = 0; var attackRate = 0.0; var attackTime = 0.0; var enemySpeed = 0.0;
function awake(){ enemyHealth = Random.Range (2,3); }
function Update () { var dist = Vector3.Distance(transform.position, thePlayer.transform.position);
if(Time.time > attackTime){ attackTime = Time.time + attackRate;
} }
function OnControllerColliderHit(other: ControllerColliderHit) {
if(other.gameObject.tag == "Player"){ enemyHealth --; print("Player Has Hit Me!");
}
if(enemyHealth <= 0){ Destroy(gameObject);
}
}
Answer by henry96 · Jul 03, 2012 at 04:39 AM
The health drops fast because it hits the enemy repeatedly. When it collides, it keeps on colliding, and that's what subtract the health so fast. So, create a boolean. Check if it hits the enemy. If it does, then subtract the health and wait 2 or 3 seconds until the health can be decreased once again.
For example :
//For checking if we are being hit
var beingHit : boolean = false;
if(hit.gameObject.tag == "enemy1" || hit.gameObject.tag == "enemy2"){
//Check: Subtract health only once per hit
if (!beingHit) {
playerHealth -= 5;
beingHit = true;
canBeHitAgain ();
}
}
function canBeHitAgain () {
//Wait for a few second. Then we can subtract health again
yield WaitForSeconds (2);
beingHit = false;
}
Hope this helps!