UGUI不规则形状按钮

作者:new 分类: 各种技巧 发布于:2016-3-3 5:51 ė次浏览 6条评论
using UnityEngine;
using System;
using System.Collections;
using UnityEngine.UI;
public class RaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
 private RectTransform rectTransform;
 private Image image;
 public void Awake()
 {
  collider2D = GetComponent<BoxCollider2D>();
  image = GetComponent<Image>();
 }
 public bool IsRaycastLocationValid(Vector2 screenPosition, Camera raycastEventCamera) //uGUI callback
 {
  if (image == null)
   return true;
  Vector2 localPoint;
  RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPosition, raycastEventCamera, out localPoint);
  var normalized = new Vector2(
   (localPoint.x + rectTransform.pivot.x*rectTransform.rect.width)/rectTransform.rect.width,
   (localPoint.y + rectTransform.pivot.y*rectTransform.rect.height)/rectTransform.rect.width);
  Rect rect = image.sprite.textureRect;
  var x = Mathf.FloorToInt(rect.x + rect.width * normalized.x);
  var y = Mathf.FloorToInt(rect.y + rect.height * normalized.y);
  try
  {
   return image.sprite.texture.GetPixel(x,y).a > 0.2f;
  }
  catch (UnityException e)
  {
   Debug.LogError("Mask texture not readable, set your sprite to Texture Type 'Advanced' and check 'Read/Write Enabled'");
   Destroy(this);
   return false;
  }
 }
}

本文出自 码农,转载时请注明出处及相应链接。

0

发表评论

电子邮件地址不会被公开。必填项已用*标注


Ɣ回顶部