开启辅助访问
 找回密码
 注册帐号

扫一扫,访问微社区

首页   >   博客   >   yanis

鼠标坐标转换成UGUI上的坐标,附带小功能

个人分类: Unity知识点 | 2017-10-10 17:34
标签:UGUI 坐标转换

[code]csharpcode:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class OverUIFloat :MonoBehaviour {

    public GameObject[] objects;

    private Vector3 rectPos;    //UGUI组件的坐标
    private RectTransform rectTransform;
    private float xMin;
    private float xMax;
    private float yMin;
    private float yMax;
    private Canvas canvas;

    private Vector2 pos =  Vector2.one;

    void Start()
    {
        canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        rectTransform = GetComponent<RectTransform>();  
    }

    private void Update()
    {
        //需要除以scale缩放倍数才能得出真正的坐标
        rectPos = new Vector3(rectTransform.position.x / canvas.transform.localScale.x, rectTransform.position.y / canvas.transform.localScale.y, 0);  
        xMin = rectPos.x+ rectTransform.rect.xMin;
        xMax = rectPos.x + rectTransform.rect.xMax;
        yMin = rectPos.y + rectTransform.rect.yMin;
        yMax = rectPos.y + rectTransform.rect.yMax;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out pos);
        //if (Input.GetMouseButtonDown(0))
        //{
        //    Debug.Log("RectPos:" + rectPos);
        //    Debug.Log("pos.x:" + pos.x);
        //    Debug.Log("pos.y:" + pos.y);
        //    Debug.Log("xMin:" + xMin + "xMaxn:" + xMax + "yMin:" + yMin + "yMax:" + yMax);
        //}
        //因为获得的坐标是以canvas中点为原点的,这里使用1920*1080为分辨率
        if (pos.x+960 >= xMin && pos.x + 960 <= xMax && pos.y + 540 >= yMin && pos.y + 540 <= yMax)   
        {
            foreach (GameObject g in objects)
            {
                g.SetActive(true);
            }
        }
        else
        {
            foreach (GameObject g in objects)
            {
                g.SetActive(false);
            }
        }
    }
}

0 0

作者的其他最新博客

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册帐号

个人分类

标签

阅读排行

评论排行

推荐博客

最新博客

返回顶部