使旋转对象与父对象一起旋转

本文关键字:旋转 对象 一起 | 更新日期: 2023-09-27 18:27:50

我有一个游戏对象,它沿着其中一个轴来回摆动,它附着在一个在场景中移动的父gameObject上。但是,当父对象旋转时,子对象不会随之旋转。

我认为这与本地空间与全球空间有关。。然而我不知所措。。。

这是管理扫描的代码。

    // Increment a timer
    timer += Time.deltaTime;
    // Swing the object back and forth based on the rotationLimit and the rotationSpeed
    currentRotation = Mathf.PingPong (timer * rotationSpeed, rotationLimit * 2f) - rotationLimit;
    // Create a temporary variable to store the new rotation
    Quaternion rotation = Quaternion.Euler (transform.rotation.x, transform.rotation.y + currentRotation, transform.rotation.z);
    // Set the rotation to the temp var
    transform.rotation = rotation;

我考虑过抓取父对象的旋转,并使用它来代替transform.rrotation。然而,理想情况下,这个脚本需要处理各种对象,其中一些对象没有父对象。有人能告诉我哪里出了问题吗。

使旋转对象与父对象一起旋转

根据您的标签,我猜您使用的是Unity。据我所知,统一支持"场景图"的概念。这允许您构建游戏对象树,其中子对象跟随其父对象的变换。请参阅此链接:http://docs.unity3d.com/ScriptReference/Transform-parent.html

备选方案-如果您想手动执行此操作:

手动组合父级/子级转换时,应小心谨慎。做到这一点最简单也是最好的方法是简单地将父转换和子转换结合起来:

ChildWorldTransform = ChildLocalTransform * ParentWorldTransform

ChildLocalTransform对应于当前Rotation,ParentWorldTransform对应父对象的转换。请注意,应该将整个变换作为一个整体相乘,而不仅仅是旋转部分!

我还建议你在谷歌上搜索"scenegraph"