简体   繁体   English

有没有办法仅在 Y 轴上使用 Quaternion.LookRotation() 旋转游戏对象?

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

So, I'm working on Unity project.所以,我正在开发 Unity 项目。 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.但是将 y 设置为 0 将 x 轴的旋转上限设置为 0,但我希望我的迫击炮向前倾斜一点。 I've tried setting y to many different values but then distance between two objects determines how much the mortar leans.我尝试将 y 设置为许多不同的值,但是两个物体之间的距离决定了迫击炮的倾斜程度。 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.我唯一的想法是计算两个游戏对象之间的距离并相应地更改 directionToFace.y 的值。 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但是我必须在检查器中获得分配给迫击炮的局部旋转,然后使用勾股定理计算值......但我不想那么折磨自己: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.其中 xOffset 是您希望游戏 object 倾斜的量,也可以以类似的方式为 z 添加显式值。

旋转对象

Let me know if this isn't what you meant.如果这不是你的意思,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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