unity计算多个物体的的中心点

为什么有这个需要,原因是如果一个父物体下有很多子物体,此时如果要做摄像机的旋转,那么摄像机肯定要定位一个目标点,,要求这个目标点至少要在众多物体的中心,这样旋转的体验会非常好,如何做呢,看下面的一个小demo


这里写图片描述


程序运行一下:
这里写图片描述


public class delete : MonoBehaviour {
    public Transform parent;    //这个parent下面挂着四个物体
    public GameObject tt;   //这个物体是为了说明清楚计算后的中心点的位置的
    // Use this for initialization
    void Start () {
        tt.transform.position = GetCenter(parent);
    }

    // Update is called once per frame
    void Update () {

    }
    //计算模型的中心点
    public static Vector3 GetCenter(Transform tt)
    {

        Transform parent = tt;

        Vector3 postion = parent.position;

        Quaternion rotation = parent.rotation;

        Vector3 scale = parent.localScale;

        parent.position = Vector3.zero;

        parent.rotation = Quaternion.Euler(Vector3.zero);

        parent.localScale = Vector3.one;

        Vector3 center = Vector3.zero;

        Renderer[] renders = parent.GetComponentsInChildren<Renderer>();

        foreach (Renderer child in renders)
        {
            center += child.bounds.center;
        }

        center /= parent.GetComponentsInChildren<Renderer>().Length;

        Bounds bounds = new Bounds(center, Vector3.zero);

        foreach (Renderer child in renders)
        {

            bounds.Encapsulate(child.bounds);

        }

        parent.position = postion;

        parent.rotation = rotation;

        parent.localScale = scale;

        foreach (Transform t in parent)
        {

            t.position = t.position - bounds.center;

        }



这里写图片描述


FR:徐海涛(Hunk Xu) (QQ技术交流群:386476712)

Unity 2D中,要让多个物体围绕一个共同的中心点旋转,你可以使用Transform组件中的Rotate()方法,配合Vector3结构体来控制旋转的行为。以下是基本步骤: 1. **创建物体中心点**: - 创建多个SpriteRenderer(如果需要视觉效果)或Collider(用于碰撞检测)的对象,并将它们添加到场景中。 - 设定一个GameObject作为旋转中心,通常将其设为静态以便其他对象围绕它移动。 2. **获取旋转中心位置**: - 获取或设置旋转中心的游戏物体的Transform实例,例如`GameObject centerObj = GameObject.Find("CenterObject");` 3. **为每个物体编写旋转脚本**: - 给每个需要绕中心旋转的物体添加一个Update()或Coroutine,如使用`IEnumerator`。 - 在脚本中,获取当前物体的位置和旋转中心的位置。 ```csharp Transform self = GetComponent<Transform>(); Vector3 centerPos = centerObj.transform.position; ``` 4. **计算旋转角度**: - 计算当前物体中心点之间的相对距离向量以及所需的角度。 ```csharp Vector3 relativePos = self.position - centerPos; float angle = Mathf.Atan2(relativePos.y, relativePos.x) * Mathf.Rad2Deg; ``` 5. **应用旋转**: - 使用Calculate Rotation公式来更新物体的旋转。 ```csharp float rotationSpeed = 10f; // 自定义旋转速度 self.rotation = Quaternion.Euler(0, 0, angle + rotationSpeed * Time.deltaTime); ``` 6. **循环执行**: - 将上述代码放入Update()或Coroutine中,使其持续运行并实时更新物体的旋转。 记得给你的脚本加上`public float RotateSpeed`这样的公共属性,这样可以在编辑器内调整旋转的速度。如果你希望物体只在特定条件下才开始旋转,可以添加相应的条件判断。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值