untiy中不规则物体添加collider,比如地图

方法一:直接使用编辑器来做

using UnityEngine;
using UnityEditor;
using System.Collections;

/// <summary>
/// 在给不规则sprite添加boxCollider的时候,box的蓝色边框不显示,要是规则的物体添加会box的蓝色边框会很好的显示出来,
/// 意味着box很好的裹住了物体,不规则的物体添加box时用的是Polygoncollider,但是没有很好的裹住物体,原来是NGUI默认创建的贴图和精灵的scale 都是1, 而所有的Collider都是根据GameObject的scale去算的。所以它太小了
/// ,小到了你的眼睛都完全看不到。为了方便编辑还是写一条简单的脚本来创建Polygon Collider2D。
/// </summary>
public class AddPolygonCollider2D_Demo : Editor
{
    [MenuItem("NGUI/Attach/PolygonCollider2D")]
    public static void AddPolugonCollider2D()
    {
        if(Selection.activeGameObject != null)
        {
            foreach(GameObject go in Selection.gameObjects)
            {
                UIWidget widget = go.GetComponent<UIWidget>();
                if(widget != null)
                {
                    PolygonCollider2D polygoncllider = go.GetComponent<PolygonCollider2D>();

                    if(polygoncllider == null)
                    {
                        polygoncllider = go.AddComponent<PolygonCollider2D>();
                    }

                    Vector2[] vectors = new Vector2[4];
                    int widthHalf = (widget.width >> 1) + 20;
                    int heightHalf = (widget.height >> 1) + 20;
                    vectors[0] = new Vector2(-widthHalf, -heightHalf);
                    vectors[1] = new Vector2(widthHalf, -heightHalf);
                    vectors[2] = new Vector2(widthHalf, -heightHalf);
                    vectors[3] = new Vector2(-widthHalf, -heightHalf);
                    polygoncllider.points = vectors;
                }
            }
        }
    }
}

代码写完之后使用,点击shift和鼠标左键进行编辑collider的范围

 

方法二:

直接在物体的inspects面板进行修改,首先添加polygoncollider来,然后在面板中点击右上角的小图标,选择debug,进行如编辑

 

提示:

但是NGUI现在的代码是不支持PolygonCollider2D的。原因是NGUI用的是3D射线,而PolygonCollider用的是2D射线,射线是需要每一帧Update都要去判断的。

posted @ 2015-04-16 10:21  小歪歪Frank  阅读(6325)  评论(0编辑  收藏  举报