Hi!
I’m writing a simple enemy AI for a game I’m making, and as of now it should just have two different attacks which would be picked randomly(even tho its just one or the other, but hey…) here’s how it should be working:
I made a “dice” that will only generate a number when the player is in range, then stop.
If the player is in range the enemy will start attacking based on what number was thrown and turn the dice back on afterwards.
The dice will generate a new number and the next attack should follow.
It does this pretty nicely some times, however sometimes it simply keeps throwing numbers making the enemy use multiple attacks at the time.
I can’t seem to find out why tho, does anybody know where I went wrong?
Here’s the script:
var player : GameObject;
var distToPlayer : float;
var attackDice : int;
var attackRange : float;
var canRoll = true;
function Start()
{
findPlayer();
attackRange = 15;
canRoll = true;
}
function Update ()
{
checkPlayerInRange();
if (distToPlayer > attackRange)
{
canRoll = false;
attackDice = 100;
}
if (canRoll != false)
{
rollDice();
}
}
function checkPlayerInRange()
{
var distance = Vector3.Distance(transform.position, player.transform.position);
distToPlayer = distance;
if (distToPlayer < attackRange)
{
Attack();
lookAtMe();
if(attackDice == 100)
{
attackDice = 6;
}
}
}
function findPlayer()
{
player = GameObject.FindWithTag("Player");
}
function Attack()
{
if (attackDice >5 && attackDice < 11)//use breath attack
{
flamethrower = transform.Find("Wisp");
animation.CrossFade("firebreath");
yield WaitForSeconds(1.5);
flamethrower.particleEmitter.emit = true;
if (distToPlayer < 10)
{
player.GetComponent("PlayerHealth").curHealth -= 1;
}
yield WaitForSeconds(1.5);
flamethrower.particleEmitter.emit = false;
attackDice = 0;
canRoll = true;
}
if (attackDice > 0 && attackDice < 6)//use sword attack
{
animation.CrossFade("swordslash");
if (distToPlayer < 5)
{
player.GetComponent("PlayerHealth").curHealth -= 3;
}
yield WaitForSeconds(2);
attackDice = 0;
canRoll = true;
}
else
{
animation.CrossFade("idle");
}
}
function rollDice()
{
var rolledDice : int = Random.Range(1,10);
attackDice = rolledDice;
canRoll = false;
}
function lookAtMe()
{
var lookPos = player.transform.position - transform.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 2);
}