What you will learn: how to make an enemy attack your character with a different attack, based on a percent, every 2 seconds. The attack will make your health go down.

Creating the MovieClips:

1. Make a character MovieClip.

2.Make a healthbar.

3. Make the enemy:

  • create three frames within the enemy with a movieclip inside each frame
  • put the stop; action on each frame
  • Make sure the end of each MC within the frame has this actionscript on their last frame: _root.enemy.gotoAndStop(‘standing’);//since we do not want the attack to loop, we send it to the standing frame.
  • one frame is the enemy standing still (label standing)
  • another is the enemy’s first attack (label the frame attack1)
  • the last is the enemy’s second attack (label the frame attack2)

1. First you’ll need to be able to move your character MC. To do this use a basic movement code:

onClipEvent(enterFrame){//every frame
if(Key.isDown(Key.LEFT)){//if left key is down
this._x-=5;//this moves 5 pixels to the left
}
if(Key.isDown(Key.RIGHT)){//if the right key is down
this._x+=5;//this moves 5 pixels to the right
}
}

2. Give your character the instance name player.

3. Now you will need a health bar. Use the tutorial here.

4. Now, give your health bar the instance name healthbar.

5. Next, put this code onto the frame:

enemyTimer=40;//creats a variable called enemyTimer with a value of 40 (2 seconds)
_root.healthbar.gotoAndStop(100);//healthbar stops at frame 100
onEnterFrame= function(){//every frame
if (_root.enemyTimer==0){//if the timer equals 0
_root.enemyTimer=40;//the timer resets to 40
} else _root.enemyTimer-=1;//otherwise, the time goes down by 1 every frame
}

6. Finally, you can add the A.I code to your enemy. Put in his MC:

onClipEvent(enterFrame){//event that happens every frame
distance= _root.enemy._x- _root.player._x;//declares a variable called distance that tells the distance between the player and enemy
if(distance<100 && distance >-100 && _root.enemyTimer==0){//if the distance between the player and enemy is less than 100, greater than -100 and the timer equals 0
rNumber=int(Math.random()*100)//creates var rNumber which is an random integer between 1 and 100
if(rNumber >=0 && rNumber <60){//if a is greater than 0 and less than 60
_root.enemy.gotoAndStop(‘attack1′);//enemy goes to attack frame 1
_root.healthbar.gotoAndStop(_root.healthbar._currentframe -= 5);//healthbar goes down by 5
} else if (rNumber>=60 && rNumber<=100){//if a is between 60 and 100
_root.enemy.gotoAndStop(‘attack2′);//enemy goes to attack frame 2
_root.healthbar.gotoAndStop(_root.healthbar._currentframe -= 8);//health goes down by 8
}
}
}

7. Test your file. You should be able to move your character over to the enemy and have the enemy attack you, making your healthbar go down.

8. Here is what the final product should look like.

Related posts:

  1. Basic A.I Tutorial: Enemy Attacks and Movement