在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大小
            }
        }
    }
}
相关推荐
QC·Rex9 小时前
Spring AI MCP Apps 实战:打造聊天与富 UI 融合的智能化应用
人工智能·spring·ui·spring ai·mcp
ai_coder_ai11 小时前
自动化脚本ui编程之帧布局(frame)
ui·autojs·自动化脚本·冰狐智能辅助·easyclick
天天进步201512 小时前
不止于 UI:OpenWork 的核心哲学与“引擎+外壳”架构全景图
人工智能·ui·架构
星辰即远方12 小时前
UI学习3
学习·ui
比老马还六16 小时前
element-ui,使用el-table时,type=“expand“和fixed一起使用坑
开发语言·javascript·ui
星河耀银海16 小时前
Unity基础:UI组件详解:Button按钮的点击事件绑定
ui·unity·lucene
UnicornDev16 小时前
【HarmonyOS 6】练习记录页面 UI 设计
ui·华为·harmonyos·arkts·鸿蒙
CodeForCoffee16 小时前
Adobe illustrator将AI绘制图片转换为矢量图
ui·adobe·illustrator
RReality17 小时前
【Unity Shader URP】平面反射(Planar Reflection)实战教程
ui·平面·unity·游戏引擎·图形渲染·材质
汽车芯猿17 小时前
压扁的图像:嵌入式设备中的长方形像素之谜
嵌入式硬件·ui·photoshop