在ui上使用boxcollider的问题

  • 问题就是boxCollider不会随着UI缩放而缩放
  • 这个问题也很简单
  • 下面脚本可以实现随着recttransform来同步设置boxcollider
csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxColliderAdjust : MonoBehaviour
{
    public bool AdjustBoxCollider = false;
    private BoxCollider2D boxCollider2D;
    private RectTransform gameObject;
    // Use this for initialization
    void Start()
    {
        gameObject = this.GetComponent<RectTransform>();
        boxCollider2D = this.GetComponent<BoxCollider2D>();
    }
    // Update is called once per frame
    void Update()
    {
        if (boxCollider2D == null)
        {
            Debug.Log("can't find collider");
            return;
        }
        else
        {
            if (AdjustBoxCollider == true)
            {
                boxCollider2D.offset = gameObject.rect.center;      //把box collider设置到物体的中心
                boxCollider2D.size = new Vector2(gameObject.rect.width, gameObject.rect.height);    //改变collider大小
            }
        }
    }
}
相关推荐
开开心心loky11 小时前
[iOS] push 和 present Controller 的区别
ui·ios·objective-c·cocoa
眠りたいです11 小时前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
我命由我1234519 小时前
Photoshop - Photoshop 创建文档
学习·ui·课程设计·设计·photoshop·ps·美工
六月的可乐20 小时前
【干货推荐】AI助理前端UI组件-悬浮球组件
前端·人工智能·ui
我命由我123452 天前
Photoshop - Photoshop 创建图层蒙版
运维·学习·ui·课程设计·设计·ps·美工
江拥羡橙3 天前
【目录-单选】鸿蒙HarmonyOS开发者基础
前端·ui·华为·typescript·harmonyos
江拥羡橙3 天前
【目录-多选】鸿蒙HarmonyOS开发者基础
前端·ui·华为·typescript·harmonyos
XXYBMOOO4 天前
Qt UDP 通信类详解与实现
开发语言·网络·c++·qt·网络协议·ui·udp
摘星编程4 天前
Cursor Pair Programming:在前端项目里用 AI 快速迭代 UI 组件
前端·人工智能·ui·typescript·前端开发·cursorai
安卓开发者4 天前
鸿蒙Next的UI国际化与无障碍适老化实践:构建全球包容的数字世界
ui·华为·harmonyos