简体   繁体   中英

Is there a way to rotate gameobject using Quaternion.LookRotation() on Y axis only?

So, I'm working on Unity project. I have a mortar, which is leaned towards player gameobject. I want to rotate it so it follows player movement. I came up with this simple code in my Update method:

        Vector3 directionToFace = _player.position - transform.position;
        directionToFace.y = 0;
        Debug.DrawRay(transform.position, directionToFace, Color.green); // for visualization
        transform.rotation = Quaternion.LookRotation(directionToFace);

But setting y to 0 caps rotation of x axis to 0 but I want my mortar to be leaned forward a bit. I've tried setting y to many different values but then distance between two objects determines how much the mortar leans. Yes, I know that I can make it child of an empty gameobject and apply script to the parent but if there is any other way to fix this problem inside my code... Your help will be appreciated.

The only idea I have is to calculate distance between two gameobjects and change value of directionToFace.y accordingly. But I will have to get local rotation that's assigned to mortar in the inspector and then calculate the value using Pythagorean Theorem... but I don't want to torture myself that much:D

Hope I understand your problem! I found it was possible to lean your gameObject forward by adding in this line after your code

transform.rotation = Quaternion.Euler(xOffset,transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z);

where xOffset is the amount you want your game object leaning, it would also be possible to add an explicit value for z in a similar way.

旋转对象

Let me know if this isn't what you meant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM