- Home /
Enemy AI Script Glitch
Hello Unity Community, I am here to ask for some help on my Enemy AI script. I am trying to figure out a way to make a script where I can use the new Mecanim system that was introduced in Unity 4.0. My enemy seems to have a tough time deciding when to run left, right, or forward. Here is the part of the script that I am having trouble with...
var distance = (target.position - myTransform.position).magnitude;
Vector3 dir = (target.transform.position - transform.position).normalized;
float direction = Vector3.Dot(dir, transform.forward);
float dirRightLeft = Vector3.Dot(dir, transform.right);
animator.SetFloat("Speed", movingSpeed);
if(direction > 0.8f && dirRightLeft < 0.2f)
animator.SetFloat("Direction", curDir = runForward);
if(direction < 0.8f && dirRightLeft > 0)
animator.SetFloat("Direction", curDir - 0.1f * Time.deltaTime);
if(direction < 0.8f && dirRightLeft < 0)
animator.SetFloat("Direction", curDir + 0.1f * Time.deltaTime);
if(curDir > 1f)
curDir = 1f;
if(curDir < 0)
curDir = 0;
//look at target
// myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
// Quaternion.LookRotation(target.position - myTransform.position), rotSpeed * Time.deltaTime);
what is the animation that the "Direction" float is meant to activate? a screenshot of your blendtree showing what direction is meant to do would be good. also you should set how the value of curDir is changed outside the SetFloat function, because it doesnt make much sense what curDir is mean to do there.
Of course, I didn't think about giving you a screenshot of the blendtree. Here it is, as you can see curDir decides which direction to run. The closer it gets to 1, the more he runs to the right, the closer it gets to 0, the more he runs to the left, and when it get's to 0.5, he runs forward.
ya i can see what your doing wrong, but before i can answer i need to know what the 2 variables in your if condition are meant to do (direction and dirRightLeft)
Okay I edited the script in the answer to give the information you need.
I was doing some stuff to study a little more on scripting and I think using $$anonymous$$athf might help. I'll be doing some research on it tomorrow because I am a little busy with something tonight, but if you have any advice or anything, please let me know.