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. Dismiss Notice

Question How to rotate around parents Y axis

Discussion in 'Scripting' started by elliot_eserin, Feb 4, 2023.

  1. elliot_eserin

    elliot_eserin

    Joined:
    Jan 5, 2020
    Posts:
    38
    Ok so, I have a gameobject (Ill call it turret) that currently rotates around its local Y axis to look at the mouse position:

    Code (CSharp):
    1. float yRot = Mathf.Atan2(-aim.y, aim.x) * Mathf.Rad2Deg + 90;
    2. Vector3 euler = new(0, yRot, 0);
    3. transform.localEulerAngles = euler;
    Where aim is the mouse x and y position but offset so (0,0) is in the center, x and y are negative in bottom left and positive in top right etc.
    This works great, except now the parent of this turret can have a rotation that isn't (0,0,0), meaning that setting the turrets localRotation no longer works, as it also adds the rotation of the parent and no longer looks towards the mouse.

    I cannot for the life of me work out how to rewrite this so it does, given that the parents up vector wont always be world space up, so using eulerAngles rather than localEulerAngles doesn't work in my current case because I do not want to be rotating around the worldspace up, I want to be rotating around the parents up axis. How could I rewrite this so it does?

    Thanks for any help in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,749
    Don't think of it as only code. These things are always a tight coupling of code setting local rotations on things as well as a cleverly-parented hierarchy of invisible pivots and then the visible graphics below them.

    Here's some specific notes on turret aiming/rotating:

    https://forum.unity.com/threads/vector-lookat-unprecise.858511/#post-5658304
     
  3. elliot_eserin

    elliot_eserin

    Joined:
    Jan 5, 2020
    Posts:
    38
    I agree, and actually that code was really good for generating some alternative approaches, but I think the core issue is still there of, regardless of whether or not the gun is parented to the rotating object, the rotation still has to be applied around the parents up axis. I could do something like transform.RotateAround(transform.position, targetTransform.up, angleToRotate); and set the position equal to the targetTransform each frame where targetTransform is the previous parent - but I would have to work out angleToRotate which Im not sure how to do given only the mouse position and the current transforms...
    My current hierarchy is just a player container which doesn't move -> ship (which is the targetTransform and can have any rotation) -> Turret
    All of the models are separated