- Home /
Can Someone Help Me With This A.I. Script?
Hello. I recently copied some code from a post made on this forum for a simple A.I. Javascript. Everything worked for the most part, except the enemy rotates whenever they attack my player. This is fine for 3D games, but I'm working on a 2D game. For reference, here's the script:
 var target : Transform; //the enemy's target
 var moveSpeed = 3; //move speed
 var rotationSpeed = 3; //speed of turning
  
 var myTransform : Transform; //current transform data of this enemy
  
 function Awake()
 {
     myTransform = transform; //cache transform data for easy access/preformance
 }
  
 function Start()
 {
      target = GameObject.FindWithTag("Player").transform; //target the player
  
 }
  
 function Update () {
     //rotate to look at the player
     myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
     Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
  
     //move towards the player
     myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
  
  
 }
I tried changing the rotation speed to zero and commenting out the lines that set up rotation in the Update function, but my enemy doesn't move at all when I do either of those things. Am I doing something wrong, or should I come up with a new script altogether? Thanks in advance to anyone who answers this.
Answer by MrProfessorTroll · Jan 09, 2014 at 04:40 AM
Take out this part:
  //rotate to look at the player
         myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
         Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
Grab the player's transform.
 function Start()
     {
          target = GameObject.FindWithTag("Player").transform;
     }
Then check if the player is to the left or right of ai.
 if(target.position.x >= myTransform.position.x)
 {
 //The target is on the right so move to the right
 myTransform.position.x += moveSpeed * Time.deltaTime;
 //Flip the ai to face the player
 myTransform.localScale.x = 1;
 }
 if(target.position.x < myTransform.position.x)
 {
 //The target is on the left so move to the left
 myTransform.position.x -= moveSpeed * Time.deltaTime;
 //Flip the ai to face the player
 myTransform.localScale.x = -1;
 }
 
 //You might have to switch around the numbers on the myTransform.localScale.x if the ai is facing the wrong way. Good luck
Tried it out just now. It works perfectly! Thank you very much.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                