- Home /
How would I decrease a variable over time based on distance?
Hello,
I am working on my enemy AI. Basically what I am trying to do is subtract my player's health over time when in range with the enemy. I am able to subtract health from the player when within range, but because I am checking the distance between them in the Update function, my health is being subtracted very fast. How can I make it so that the health slowly decreases? Here is my code:
THANKS!
var player : Transform; var minTargetDist = 10.0; var minAttackDist = 5.0; var rotationDamping = 6.0;
private var attacking = false;
function Update () { var distBetween = Vector3.Distance(player.position, transform.position);
if (distBetween <= minTargetDist) {
var rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
else {
return;
}
if (distBetween <= minAttackDist) {
if (attacking) {
Attack();
}
else {
attacking = true;
}
}
else {
return;
}
}
function Attack() { var damage = 2 * Time.time;
player.GetComponent(PlayerHealth).health -= damage;
}
Answer by Rod-Green · Dec 28, 2011 at 05:46 AM
There's two ways to do this, either:
a) limit the time between the attacks something like this:
var player : Transform;
var minTargetDist = 10.0;
var minAttackDist = 5.0;
var rotationDamping = 6.0;
var attackTime = 1.0;
var damage = 1.0;
private var attacking = false;
private var lastAttackTime = -100.0;
function Update () {
var distBetween = Vector3.Distance(player.position, transform.position);
if (distBetween <= minTargetDist) {
var rotation = Quaternion.LookRotation(player.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * rotationDamping);
}
else {
return;
}
if (distBetween <= minAttackDist) {
if (attacking) {
Attack();
}
else {
attacking = true;
}
}
else {
return;
}
}
function Attack()
{
if(Time.time - lastAttackTime < attackTime)
return;
lastAttackTime = Time.time;
player.GetComponent(PlayerHealth).health -= damage;
}
or B) Use deltaTime rather than time to do 'progressive' damage
var damage = 2 * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Increase health smoothly not instantly? 2 Answers
Calculate the distance a object has moved. 3 Answers
Health Regeneration 2 Answers
How can i make my health regenerate? 1 Answer
Adding 1 to a float over time to increase difficulty? 3 Answers