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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Turret Rotation Issue

Discussion in 'Scripting' started by yepfuk, Sep 23, 2015.

  1. yepfuk

    yepfuk

    Joined:
    Sep 23, 2015
    Posts:
    67
    Hi,

    I have a problem about rotating a turret... I want to rotate my turret only z rotation, where the target objects is, but my turret's x rotation also changes but i don't want this. How can i fix this issue?

    My turret rotation code;


    void Update()
    {
    newRotation = Quaternion.LookRotation(target.transform.position - transform.position, Vector3.forward);
    newRotation.x = 0.0f;
    newRotation.y = 0.0f;

    transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * rotationSpeed);
    }

    Edit : The code works perfectly fine , source of the problem is the model that I use... Thank you for your replies...
     
    Last edited: Sep 23, 2015
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    you are trying to modify the x and y attribute of a quaternion. Quaternions are NOT represented in xyz axis... don't do this.

    If you want to work with rotations around xyz axis you need to use the euler or eulerangles functions/attributes
     
  3. Smingleigh

    Smingleigh

    Joined:
    Nov 24, 2012
    Posts:
    9
    I'd try getting the vector that represents the line to the target and zeroing out the vertical part, so that it doesn't even try to pitch up or down.

    How about this (formatted with code tags for easier reading)

    Code (csharp):
    1. void Update()
    2. {
    3.     Vector3 direction = target.transform.position - transform.position;
    4.     newRotation = Quaternion.LookRotation(new Vector3(direction.x, 0f, direction.z), Vector3.up);
    5.     transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * rotationSpeed);
    6. }
    I'm not sure what you're going for axis-wise, so you might have to change the LookRotation's up and which component of the direction to zero to get the result you want.

    You might find further useful information here.
     
    Last edited: Sep 23, 2015
  4. yepfuk

    yepfuk

    Joined:
    Sep 23, 2015
    Posts:
    67
    I tried your code but resut is same unfortunately :( But I also tried my code to another object that I create, and works perfectly. I think the problem is my imported turret object, but I don't know how to fix it :( Thank you by the way...