1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

オブジェクトがBoxColliderの中に完全に入っているかどうか判定する

Last updated at Posted at 2021-02-26

オブジェクトが完全にコライダーの中に入っているかどうか?を判定するためのコードを組みました。

BoxCheck01.png
BoxCheck02.png
BoxCheck03.png

BoxColliderの各面をPlaneとして取得するスクリプト

Vector3操作スクリプト(ランダム方向、要素の最大値を取得)
はこの処理をするためのものです

ColliderFullyInsideCheck.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColliderFullyInsideCheck: MonoBehaviour
{
    private Material material;
    private Color DefaultColor;
    private Color ChangeColor = Color.green;

    public SphereCollider TargetCollider;

    void Awake()
    {
        material = GetComponent<MeshRenderer>().material;
        DefaultColor = material.GetColor("_Color");
    }

    public bool isColorChange
    {
        set
        {
            material.SetColor("_Color", value ? ChangeColor : DefaultColor);
        }
    }

    public bool isColliderFullyInside(BoxCollider box, SphereCollider sphere)
    {
        float radius = Calc.MaxElementOfVector3(sphere.transform.lossyScale) * sphere.radius;
        Vector3 center = sphere.transform.TransformPoint(sphere.center);

        int inside_count = 0;
        Plane[] planes = Calc.GetBoxColliderPlanes(box);
        for (int i = 0; i < 6; i++)
        {
            float inside_distance = planes[i].GetDistanceToPoint(center);
            if (-inside_distance >= radius)
            {
                inside_count++;
            }

        }
        return inside_count == 6;
    }

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        isColorChange = isColliderFullyInside(GetComponent<BoxCollider>(), TargetCollider);
    }
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?