在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大小
            }
        }
    }
}
相关推荐
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_50:(深入理解 DOM 中的 Text 节点)
前端·javascript·microsoft·ui·html·媒体
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_51:(深入理解 XPathEvaluator 接口)
前端·javascript·ui·html·音视频
键盘飞行员3 小时前
Windsurf + Claude 4.7 前端开发:用 ui-ux-pro-max 根治 “AI 味”、实现全站 UI 统一
前端·ui·ai编程
ZC跨境爬虫4 小时前
跟着 MDN 学 HTML day_53:(深入理解 XPathResult 接口)
前端·javascript·ui·html·音视频
tedcloud12310 小时前
UI-TARS-desktop部署教程:构建AI桌面自动化系统
服务器·前端·人工智能·ui·自动化·github
ZC跨境爬虫13 小时前
跟着MDN学HTML_day_48:(Node接口)
前端·javascript·ui·html·音视频
为何创造硅基生物14 小时前
嵌入式 LVGL / SquareLine UI 标准命名规则(行业通用版)
windows·ui
AITOP1001 天前
高德联合千问开源AGenUI:让Agent UI同时跑在iOS、安卓和鸿蒙上
ui·ios·开源
UXbot1 天前
AI原型设计工具如何从PRD自动生成交互原型
前端·低代码·ui·交互·ai编程·原型模式
十五年专注C++开发1 天前
QFluentKit: 一个基于 Qt Widgets 的 Fluent Design 风格 UI 组件库
开发语言·c++·qt·ui·qfluentkit