Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to prevent rotation on the Z axis ?

Discussion in 'Physics' started by Javed_Wilde, Jan 30, 2018.

  1. Javed_Wilde

    Javed_Wilde

    Joined:
    Jan 25, 2018
    Posts:
    3
    I'm making an enemy script which enables the enemy object to look towards the player and follow it.
    But what is happening here is whenever the player jumps , the enemy tilts itself on the z axis and starts to float in the air.
    I tried adding constrains using the rigidbody component but it didn't work.
    i tried to add a Quaternion (zClamp) and set it's value to zero but it didn't work either.

    Adding gravity disables it to fly upwards but then the bullet impact force creates some weird stuff.

    I'm just removing the extra variables, functions and other stuff to just let u focus on the rotation system only.
    I'm also removing the definations cuz they are self explanatory.

    Code (CSharp):
    1.  
    2.  
    3. public class EnemyControl : MonoBehaviour {
    4.  
    5.     // Use this for initialization
    6.     void Start () {  
    7.     }
    8.  
    9.    
    10.     // Update is called once per frame
    11.     void Update () {
    12.  
    13.         if (enemyActive && playerDistance > 1f) {
    14.             Quaternion rotation = Quaternion.LookRotation (player.position - transform.position);
    15.             transform.rotation = Quaternion.Slerp (transform.rotation, rotation, Time.deltaTime * 10);
    16.  
    17.             // I tried to use this
    18.             Quaternion zClamp = transform.rotation;
    19.             zClamp.eulerAngles = new Vector3 (zClamp.eulerAngles.x, zClamp.eulerAngles.y, 0);
    20.  
    21.  
    22.             transform.rotation = zClamp;
    23.             transform.Translate (Vector3.forward * speed * Time.deltaTime);
    24.         }  
    25. }
    26.  


    Any help would be appreciated !!
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Try by ignoring the y portion of the look direction.
    Code (csharp):
    1. Vector3 lookdir = player.position - transform.position;
    2. lookdir.y = transform.position.y;
    3. // the rest of your code, not worrying about the difference in 'y'
    4.  
     
    Javed_Wilde likes this.
  3. Javed_Wilde

    Javed_Wilde

    Joined:
    Jan 25, 2018
    Posts:
    3
    Thanks!!
    It Works !!!
    I spent days, finding fixes and messing up with quaternions .

    Though the answer was SO SIMPLE.

    Thanks for the help!
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Cool, you're welcome. :)