在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大小
            }
        }
    }
}
相关推荐
jllllyuz9 小时前
基于ASP.NET Core SignalR实现实时消息提醒与聊天功能
ui·asp.net·xhtml
梦想的旅途210 小时前
RPA 脚本的“自愈”能力:应对企微 UI 频繁更新
ui·企业微信·rpa
IT古董11 小时前
企业级官网全栈(React·Next.js·Tailwind·Axios·Headless UI·RHF·i18n)实战教程-前言
javascript·react.js·ui
Larry_Yanan20 小时前
Qt多进程(三)QLocalSocket
开发语言·c++·qt·ui
xinyu_Jina1 天前
Calculator Game:WebAssembly在计算密集型组合优化中的性能优势
前端·ui·性能优化
前端不太难1 天前
Navigation State 与页面内存泄漏的隐性关系
前端·ui·react
lovingsoft1 天前
复用的Vibe Coding 提示词模板(含原型 / MVP、CRUD、UI 组件、调试反馈 4 类场景)
人工智能·ui·敏捷开发
深蓝海拓1 天前
PySide6从0开始学习的笔记(十四)创建一个简单的实用UI项目
开发语言·笔记·python·qt·学习·ui·pyqt