Unity-背包系统-利用矩阵进行范围检测

矩阵检测:原理

          在Unity中有时候,你需要用到检测的时候。虽然 Unity有内置提供的方法,但是那并不能对你有多大帮助;比如常见的有 :
          1、 OnTrigger2D()函数
          2、接口事件
          3、Button进入事件
          4、UIEvent
          、、、、、
          等等但是这些都不是我们想要的效果,不是因为这个就是因为那个。反正就是不爽,而且条件多,所以笔者这里给大家介绍一个原生态的鼠标进入矩阵的时候产生交互。
先上效果图:
当我的鼠标不在范围内的时候返回 false
不在矩阵内的时候
只要检测到我的鼠标在范围内的时候,返回true(也就是我),这里画的有点水货。不要嫌弃哈哈
在这里插入图片描述
在上代码之前先看一点东西:

using System;
using UnityEngine;

public class Matrix : MonoBehaviour {
    void Update () {
        //Vector2 ve = RectTransformUtility.WorldToScreenPoint(Camera.main,Input.mousePosition);
        float X = Input.mousePosition.x - Screen.width / 2f;
        float Y = Input.mousePosition.y - Screen.height / 2f;
        //Debug.Log(X);
        //Debug.Log(Y);
        //这个地方传入的是两个对角Image 的坐标
        Debug.Log(isInside(-300,300,300,-300, X, Y));
    }
    //判断一个点是否在矩形内部
    public static bool isInside(double x1, double y1, double x4, double y4, double x, double y)
    {
        //默认:1点在左上,4点在右下
        if (x <= x1)
        {//在矩形左侧
            return false;
        }
        if (x >= x4)
        {//在矩形右侧
            return false;
        }
        if (y >= y1)
        {//在矩形上侧
            return false;
        }
        if (y <= y4)
        {//在矩形下侧
            return false;
        }
        return true;
    }

    public static bool isInside(double x1, double y1, double x4, double y4,
            double x2, double y2, double x3, double y3, double x, double y)
    {
        //矩形边平行于x轴或y轴
        if (y1 == y2)
        {
            return isInside(x1, y1, x4, y4, x, y);
        }
        //坐标变换,把矩形转成平行,所有点跟着动
        double a = Math.Abs(y4 - y3);
        double b = Math.Abs(x4 - x3);
        double c = Math.Sqrt(a * a + b * b);
        double sin = a / c;
        double cos = b / c;
        double x11 = cos * x1 + sin * y1;
        double y11 = -x1 * sin + y1 * cos;
        double x44 = cos * x4 + sin * y4;
        double y44 = -x4 * sin + y4 * cos;
        double xx = cos * x + sin * y;
        double yy = -x * sin + y * cos;
        //旋转完成,又变成上面一种平行的情况
        return isInside(x11, y11, x44, y44, xx, yy);
    }
}

肯定会有小伙伴 儿问倒数第十五行以后是*****,口吐芬芳。。。。所以这里作者再加上一个宝典
转载请附博主;

发布了29 篇原创文章 · 获赞 2 · 访问量 789

猜你喜欢

转载自blog.csdn.net/zhanxxiao/article/details/104508073