简体   繁体   English

如何围绕他的轴心而不是他的中心旋转GameObject?

[英]How to rotate a GameObject around his pivot and not his center?

My goal is to rotate the engine of a plane . 我的目标是旋转飞机的引擎

My plane have 2 engines and is represent like this in my hierarchy : 我的飞机有2个引擎,并在我的层次结构中这样表示: 平面层次

If I analyze my plane from the inspector , here's what I get in Center /Global mode : 如果我从检查员那里分析飞机,这就是我在“ 中心 /全局”模式下获得的信息: 平面中心全局模式

And here's the Pivot /Global mode : 这是Pivot / Global模式: 平面枢轴全局模式

If I try to rotate my engine, here's the result : 如果我尝试旋转引擎,结果如下: 旋转引擎结果

As you can see, my engine rotate not around his pivot axis but around his center axis . 如您所见, 我的引擎不是围绕他的枢轴旋转,而是围绕他的中心轴旋转 How can I make it rotate around his pivot axis ? 如何使其绕其枢轴旋转?

The code I call to make it rotate : 我调用使其旋转的代码

foreach(Transform child in planeId_Object_Dictionnary[newPlane.Flight].transform){

           if (child.name == "Engine"){
                     child.Rotate(new Vector3(0, 30, 0) * Time.deltaTime*100, Space.Self);
           }
}

The Pivot point of the 3D model is not centered . 3D模型的枢轴点未居中 Since you have 3DSMax, it is better to center the pivot point from a 3D software so that you don't need to create new dummy GameOject to be used as the center point. 由于您具有3DSMax,因此最好从3D软件对中心点进行居中,这样就无需创建新的虚拟GameOject用作中心点。 Watch this video to see how to center the pivot point. 观看视频,了解如何使枢轴点居中。 Just select the Engine and click the Center to Object button. 只需选择引擎,然后单击“ 中心到对象”按钮即可。 You should so the-same to all the other parts of the plane. 您应该与飞机的所有其他部分相同。 Save and re-import it to Unity again. 保存并再次将其重新导入到Unity中。

Your code 您的密码

if (child.name == "Engine")
{
    child.Rotate(new Vector3(0, 30, 0) * Time.deltaTime*100, Space.Self);
}

is not efficient. 效率不高。 Don't compare GameObject by name. 不要按名称比较GameObject。 Compare it by instance , instance id or by tag . 通过instanceinstance idtag In your case, tag is appropriate. 在您的情况下, tag是合适的。

Create a new tag in the Editor and name it Engine . 在编辑器中创建一个新标签,并将其命名为Engine Select all the Engine model parts then change their tags to Engine. 选择所有引擎模型零件,然后将其tags更改为引擎。 Now, you can use the code below which is more efficient and does not allocate memory. 现在,您可以使用下面的代码,它更高效并且不分配内存。

if (child.CompareTag("Engine"))
{
    child.Rotate(new Vector3(0, 30, 0) * Time.deltaTime * 100, Space.Self);
}

You create a empty gameobject and place it at where you want to rotate. 您创建一个空的游戏对象并将其放置在要旋转的位置。 The thing you want to rotate, make child of that empty gameobject. 您想旋转的东西,使该空游戏对象成为子对象。 Now rotate that game object. 现在旋转该游戏对象。

transform.Rotate(new Vector3(0, 30, 0) * Time.deltaTime*100, Space.Self);

This will make object rotate. 这将使对象旋转。

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

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