物体的中心点(pivot)不在中心(center)的时候,如何获取中心位置,并让物体绕中心位置旋转

前言

很多时候,我们需要让一个物体绕自己中心的某个轴进行旋转,然而,它的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);
    }
}

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值