在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大小
            }
        }
    }
}
相关推荐
传奇开心果编程8 小时前
【SwiftUI提高练中学】第13课 实时活动与灵动岛:ActivityKit 实战
学习·ui·ios·swiftui·swift
phltxy12 小时前
C 语言动态内存管理:从申请空间到安全释放
c语言·开发语言·ui
李少兄19 小时前
文档排版与数据处理:阿拉伯数字与罗马数字的转换
ui·xhtml·wps
狗凯之家源码网19 小时前
网址导航系统源码评测:个性 UI 与轻量化架构实战
ui·架构·网址导航系统
传奇开心果编程20 小时前
【SwiftUI入门练中学】第17课 通知与后台任务
学习·ui·ios·swiftui·swift
wshzd1 天前
LLM之Agent(107)|DeepSeek-Harness(十五)流式输出管道:从 StreamChunk 到 UI
人工智能·ui
我命由我123452 天前
Photoshop - Photoshop 快速共享作品
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
我命由我123452 天前
Photoshop - 将Photoshop图像置入其他应用程序
学习·ui·职场和发展·求职招聘·职场发展·学习方法·photoshop
bloglin999992 天前
豆包接口返回UI元素原因
ui
传奇开心果编程2 天前
【SwiftUI入门练中学】第7课 动画与手势:让界面更灵动
学习·macos·ui·ios·swiftui·swift