Reputation: 63
I am trying to make a game in which a button is clicked, and 45 health points from a healthbar goes down. I have all my coding, and it works well, but I want to make the button so that if health is less than 45, nothing is taken from the health bar. I tried using:
if(health < 45) health = health;
But it did not work out. I have a feeling the solution to this problem is easy, but I just can't figure it out. Obviously, I am very new at this all, and still find it hard to wrap my head around some concepts. This is my coding:
fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick);
var health:int = 100;
lifebar.gotoAndStop(101);
function fortyfivedownClick(event:MouseEvent):void{
health -= 45;
if(health < 0) health = 0;
else if(health > 100) health = 100;
lifebar.gotoAndStop(health + 1);
}
Upvotes: 1
Views: 70
Reputation: 1377
Use Math.max method. IT's very handy places like value normalization.
function fortyfivedownClick(event:MouseEvent):void{
health = Math.max( 45, health -= 45 );
}
Upvotes: 0
Reputation: 23
Its pretty simple actually, your event tells your health to go down by 45 and THEN checks if health is below 0, you just need to check how much health you have at the very beginning of the method and jump out of the method if it is 45 or below.
No idea if "break" works in flash, but that would be the easiest solution
eg:
function fortyfivedownClick(event:MouseEvent):void{
if (health <= 45) {
break;
}
health -= 45;
if(health < 0) health = 0;
else if(health > 100) health = 100;
lifebar.gotoAndStop(health + 1);
}
Upvotes: 0
Reputation: 16468
If I understand the question:
if(health>=45) // just add this
lifebar.gotoAndStop(health + 1);
Upvotes: 0
Reputation: 43902
Is there anything wrong with simply doing nothing at all if the health is less than or equal to 45? For example, something like this:
function fortyfivedownClick(event:MouseEvent):void {
if (health <= 45) {
return;
}
// Perform action
}
This will cause the function to exit early if the player doesn't have enough health.
Upvotes: 1