前言
很多时候,我们需要让一个物体绕自己中心的某个轴进行旋转,然而,它的pivot又不在center位置上,于是绕自身旋转成了噩梦。
解决办法无外乎下面几种:
1、在它的center位置处设置一个空物体做中心点,让这个物体围绕新设的中心点旋转——公转。【RoutateAround】
如下所示:
手工设置中心点,很难设到它的中心。
如何自动获取中心位置,如下:
myGo.GetComponent<BoxCollider>().bounds.center;
2、同上,center位置用代码获取,然后让物体绕中点的轴公转,刚开始很和谐,然后,公转是有误差的,最后就是散架。
3、代码获取中点,然后设置一个棍子在中点处,让旋转的物体作为棍子的子物体,让棍子自转。
转的稳,而且不会因为位置偏移而出现驾崩的现象。
4、总结
如果你的物体pivot位置不在center上,而且你要让该物体绕轴自转,那么:
(1)用代码获取该物体的center位置
(2)在center位置上建一个物体——中心轴
(3)把要旋转的物体作为该中心轴的子物体
(4)让中心轴带动物体自转
5、代码
代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* 原理:
* 1、获取中点位置,myGo.GetComponent<BoxCollider>().bounds.center。这一步是关键步骤。
* 2、在中心点处,创建一个圆柱体(或者空物体),并作为该物体的子物体——命名为【中心点物体】。
* 3、如果要让物体围绕中点旋转,则把【中心点物体】作为该物体的父物体,然后让“中心点物体”rotate即可。
* 实际应用中,如果BoxCollider组件在运行时不需要,可以在editor中deactive。
*/
public class getCenter : MonoBehaviour
{
[Header("要获取中点位置的物体")]
[Tooltip("有右键编辑器菜单")]
public GameObject myGo;
/// <summary>
/// 中点位置
/// </summary>
private Vector3 center;
/// <summary>
/// 获取物体的中点(center)位置,并在中点位置处创建一个圆柱体
/// </summary>
#if UNITY_EDITOR
[ContextMenu("设置中点位置")]
#endif
public void setCenterObject()
{
if (myGo.GetComponent<BoxCollider>() == null)
{
var bc = myGo.AddComponent<BoxCollider>();
center = bc.bounds.center;
DestroyImmediate(myGo.GetComponent<BoxCollider>());
}
else
{
center = myGo.GetComponent<BoxCollider>().bounds.center;
}
GameObject go1 = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
go1.transform.position = center;
go1.transform.SetParent(myGo.transform);
go1.name = "中心点物体";
Debug.Log(center);
}
}