在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大小
            }
        }
    }
}
相关推荐
Ulyanov25 分钟前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 基石——3-DOF质点弹道的高保真建模与数值稳定性分析
开发语言·python·算法·ui·系统仿真
ZC跨境爬虫1 小时前
跟着MDN学HTML_day_49:(ShadowRoot接口)
前端·javascript·ui·html·ecmascript·媒体
UXbot11 小时前
一人独立交付 UI + 前端:AI 驱动 UI 设计工具的五大功能模块深度评测
前端·低代码·ui·设计模式·交互
垂葛酒肝汤11 小时前
Unity的UI扫光效果Shader
ui·unity·游戏引擎
skilllite作者12 小时前
UI-TARS-Desktop 智能桌面自动化实战指南
ui·自动化·策略模式
梦想的颜色16 小时前
前端UI宝藏SKILL——UI/UX Pro Max
前端·ui·ux
ZC跨境爬虫20 小时前
跟着MDN学HTML_day44:(ProcessingInstruction接口)
前端·javascript·ui·html·媒体
for_ever_love__21 小时前
UI学习:数据驱动ce l l
学习·ui·ios·objective-c
ZC跨境爬虫21 小时前
跟着MDN学HTML_day_45:(EventTarget接口)
前端·javascript·ui·html·媒体
陈天伟教授21 小时前
UI-TARS Desktop
人工智能·ui