- Home /
Enemy follows the only player in rotation
2d game. My enemy is following me right and left, but when I jump, the enemy turns to me. I would like to jump when the enemy stands still while they are not looking up. How can I fix?
Script that I'm using.
 using UnityEngine;
 using System.Collections;
  
 public class EnemyAI : MonoBehaviour {
  
     public Transform target;//set target from inspector instead of looking in Update
     public float speed = 3f;
  
  
     void Start () {
  
     }
  
     void Update(){
  
        //rotate to look at the player
        transform.LookAt(target.transform.position);
        transform.Rotate(new Vector3(0,-90,0),Space.Self);//correcting the original rotation
  }
 }
Answer by AlucardJay · Apr 12, 2014 at 10:42 AM
Personally I would create a look position that uses the enemy Y instead of the target Y :
 Vector3 tgtPos = new Vector3( player.transform.position.x, transform.position.y, player.transform.position.z );
 transform.LookAt( tgtPos );
You may need a modifier on the transform.position.y depending on where the pivot of the enemy is, eg :
 Vector3 tgtPos = new Vector3( player.transform.position.x, transform.position.y + offsetY, player.transform.position.z );
Answer by Paulo-Henrique025 · Apr 11, 2014 at 09:33 PM
You can hard set the rotation:
 transform.LookAt(player.transform);
 Vector3 rot = transform.rotation;
 rot.z = 0;
 transform.rotation = Quaternion.Euler(rot);
Set to 0 the axis that you do not want to move and then assign the Vector3 to the rotation.
Thank you for responding. I inserted the code into void Update replacing the old, gives me a errrore player, can you give me some advice?
A rotation is a Quaternion, not a Vector3.
I think you mean :
 transform.LookAt(player.transform);
 Quaternion rot = transform.rotation;
 rot.eulerAngles.z = 0;
 transform.rotation = rot;
 Vector3 rot = Quaternion.Euler(transform.rotation)
Forgot to get the Vector3 from the rotation, thank you for pointing out.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                