一. 前言
游戏开发中,可能有一些不规则按钮,而且必须严格检测不规则区域是否被点击到。一个常见的例子就是地图板块按钮。
二. 最终效果
注:有同学私信说没做出来,所以我把Demo
工程上传到GitHub
中了,感兴趣的同学可以下载来学习。GitHub
地址:https://github.com/linxinfa/Unity-UIPolygon-Demo
三. 实现
1、创建UICamera
创建一个Camera
,重命名为UICamera
,设置Culling Mask
为UI
,设置相机的投射模式(Projection
)为正交模式(Orthographic
),注意主摄像机的Culling Mask
去掉UI
层。Canvas
使用Screen Space - Camera
模式,并赋值UICamera
。
注意,
UICamera
不需要Audio Listener
,直接去掉。2. UIpolygon节点
在Button
的子节点创建一个空节点(这里重命名为UIpolygon
),挂上UIpolygon
脚本(脚本代码见文章最下面),会自动挂上polygon Collider 2D
组件,将坐标归零。
3. 编辑碰撞区域
选中UIpolygon
节点,点击polygon Collider 2D
组件中的Edit Collider
旁边的按钮,即可直接编辑多边形碰撞形状。
最后要调节
Width
和Height
,确保包住整个不规则碰撞区域。5. 运行测试
6. UIpolygon代码
@H_502_153@using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
[RequireComponent(typeof(polygonCollider2D))]
public class UIpolygon : Image
{
private polygonCollider2D _polygon = null;
private polygonCollider2D polygon
{
get{
if(_polygon == null )
_polygon = GetComponent<polygonCollider2D>();
return _polygon;
}
}
//设置只响应点击,不进行渲染
protected UIpolygon()
{
useLegacyMeshGeneration = true;
}
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
}
public override bool IsRaycastLocationValid(Vector2 screenPoint, Camera eventCamera)
{
return polygon.OverlapPoint( eventCamera.ScreenToWorldPoint(screenPoint));
}
#if UNITY_EDITOR
protected override void Reset()
{
//重置不规则区域
base.Reset();
transform.position = Vector3.zero;
float w = (rectTransform.sizeDelta.x *0.5f) + 0.1f;
float h = (rectTransform.sizeDelta.y *0.5f) + 0.1f;
polygon.points = new Vector2[]
{
new Vector2(-w,-h),
new Vector2(w,h),
new Vector2(-w,h)
};
}
#endif
}
#if UNITY_EDITOR
[CustomEditor(typeof(UIpolygon), true)]
public class UIpolygonInspector : Editor
{
public override void OnInspectorGUI()
{
//什么都不写用于隐藏面板的显示
}
}
#endif
参考:http://www.xuanyusong.com/archives/3492
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。