Hi guys I am trying to create 2D platformer game and I would like to know what is the way to deal damage to player after it is not moving horizontally for x seconds.
these are pieces of code with stats and damage function
public int HP = 100;
;
public void DealDamage(int damage)
{ HP -= damage
}
I was trying to write inside update function something like that but it didnt work.
void Update()
{ if(transform.position.x == transform.position.x*(Time.deltaTime-5)){DealDamage(10);}
}
Thanks for the response!
I haven’t tested the following code, but give it a try
[Tooltip("Delay before the character takes damage.")]
public float damageDelay = 5 ;
[Tooltip("Each X seconds, the character will take damages.")]
public float damageInterval = 1 ;
[Tooltip("The ammoung of damage the character will take.")]
[Range(0, 100)]
public int damageAmount = 1 ;
public int HP = 100;
private bool isMoving = true ;
private Vector3 lastPosition ;
private float damageTimer = 0 ;
private float timeSinceLastDamage = 0;
private Transform t ;
private Start()
{
t = GetComponent<Transform>();
lastPosition = t.position ;
}
void Update()
{
isMoving = Mathf.Abs( lastPosition.x - t.position.x ) > 0.01 ;
if( !isMoving )
{
damageTimer += Time.deltaTime ;
if( damageTimer > 5 && (Time.time - timeSinceLastDamage) > damageInterval )
{
DealDamage( damageAmount ) ;
timeSinceLastDamage = Time.time ;
}
}
else
{
damageTimer = 0 ;
}
}
public void DealDamage(int damage)
{
HP -= damage
}