Search Unity

Fixed x axis rotation

Discussion in 'Scripting' started by Xhitman, Nov 25, 2015.

  1. Xhitman

    Xhitman

    Joined:
    Oct 30, 2015
    Posts:
    452
    I try to make cannon aim at enemy.

    The code work well for fixed y axis,
    but when i replace "direction.y=0" by "direction.x=0" , something go wrong.

    When the enemy is far away, it works well. However when the enemy move pass cannon in z direction, the cannon suddenly rotates in x axis and become upside down.


    Code (CSharp):
    1.    GameObject enemy = GameObject.Find("Enemy");
    2.  
    3.         Vector3 direction = enemy.transform.position - transform.position;
    4.  
    5.         direction.y = 0;
    6.      
    7.         Quaternion toRotation =  Quaternion.LookRotation(direction);
    8.        
    9.         transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, 10 * Time.deltaTime);