- Home /
Enemy move error
Hello , I have a script that makes the enemy follow the player and attack him , but the enemy does't move on a straight way , it moves on a curve way and i want him to move on a straight way , this is my code of attacking , I have another code to make the enemy looks on the player if you need it :
var distance; var lookAtDistance = 15.0; var attackRange = 10.0; var Speed = 5.0; var damping = 6.0;
private var isItAttacking = false; private var moveDirection : Vector3 = Vector3.zero; private var controller : CharacterController;
function Start (){ }
function Update (){ distance = Vector3.Distance(Body.target.position, transform.position); controller = GetComponent(CharacterController); if(controller.isGrounded) { moveDirection.z = Speed; } if(!controller.isGrounded) { moveDirection.y -= 10; } moveDirection = transform.TransformDirection(moveDirection); if(distance < lookAtDistance) { isItAttacking = false; lookAt (); }
if(distance < attackRange) { attack (); } }
function lookAt () { var rotation = Quaternion.LookRotation(Body.target.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); }
function attack () { isItAttacking = true; controller.Move(moveDirection * Time.deltaTime); }
thanks very much
Answer by aldonaletto · Dec 07, 2011 at 11:53 PM
I suspect that moveDirection.x is causing this weird behaviour: it should be zeroed to give a consistent local direction vector. You could zero it before TransformDirection, but it's simpler to use transform.forward directly, like below:
function Update (){ distance = Vector3.Distance(Body.target.position, transform.position); controller = GetComponent(CharacterController); moveDirection = transform.forward * speed; if(!controller.isGrounded) { moveDirection.y -= 10; } if(distance < lookAtDistance) { isItAttacking = false; lookAt (); } if(distance < attackRange) { attack (); } }
Answer by spike2192 · May 13, 2012 at 08:05 PM
would i be able to take a look at the move script please! i am having some trouble myself
Your answer
Follow this Question
Related Questions
bug Move Automatic 1 Answer
A way to create an invisible circle for the enemy? 4 Answers
Enemy AI Movement Decision Making 1 Answer
Multiple Enemy Collision Help 0 Answers
How to refer to a enemy health, from use that in some variables... 2 Answers