Z
Z
Zimaell2020-08-22 11:54:09
Unity
Zimaell, 2020-08-22 11:54:09

How to rotate an object without affecting the y-axis?

I need to make a smooth rotation of the object, I do this

void LookAtTarget(GameObject gameObject){
        if(gameObject != null){
            Vector3 direction = target - gameObject.transform.position;
            Quaternion rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Speed * Time.deltaTime);
            }
        }

everything turns out like this - it turns smoothly on turns, but at the same time, its body along Y also looks at the point where it is heading, that is, if the point is at 0 coordinate Y, then approaching it, it "dives", looks down.
I need it to rotate only along the X and Z axes, that is, it rotates left to right, but the Y rotation is not affected at all, how can I do this?
At the same time, Y cannot be set statically, it can change, you need to rotate it in this way so that Y remains unchanged ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
zZaKko, 2020-08-22
@Zimaell

I have two suggestions how to solve it:
1. Freeze the Y rotation in the inspector or through the code, then, if I'm not mistaken, Y will not change.
2. Create a float variable that will be equal to the rotation in y that is now (what you need) and in the method after the rotation, return the rotation in y to the value that was before the rotation. Something like this:

float stay_y;
void Start()[
stay_y = transform.rotation.y; //Берешь значения y до поворота
}

void LookAtTarget(GameObject gameObject){
        if(gameObject != null){
            Vector3 direction = target - gameObject.transform.position;
            Quaternion rotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Speed * Time.deltaTime);
transform.rotation = new Quaternion(transform.rotation.x, stay_y, transform.rotation.z);//Возвращаешь rotation по y  на значение до поворота.
            }
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question