Unity 获取鼠标点击图片时 获取点击位置的像素

脚本要求:

需要获取颜色的图片以走下角为起点建立空物体 右上角建立空物体(两个空物体均设置为图片的子物体,设置好锚点,将坐标改为0即可)。建立好碰撞体(BoxCollider)。用2DBoxCollider的话从摄像机发射的射线无法检测到图片。
实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MouseChooseColorTest : MonoBehaviour
{
    //选择颜色时用来检测是否是点击的选择颜色的图片
    //public RayMake rayMake;

    //计算鼠标点击位置 对应的像素位置
    public Transform textureOrigin;
    public Transform textureUPEnd;


    //存储点击的图片的texture2D getpixel() 使用
    private Texture2D clickTexture2D;
    //存储鼠标点击位置的像素值
    private Color testColor;

    //存储计算出来的像素点的位置
    private Vector2 colorPos;

    //存储图片定位点的屏幕坐标
    private Vector3 textureOriginScreenPosition;
    private Vector3 textureEndUPScreenPosition;



    //测试用的显示颜色的图片
    public Image image;

    private void Start()
    {
        //rayMake.RayHitObj += HitColorChooseImage;
        textureOriginScreenPosition = Camera.main.WorldToScreenPoint(textureOrigin.position);
        textureEndUPScreenPosition = Camera.main.WorldToScreenPoint(textureUPEnd.position);
    }

    private void HitColorChooseImage(RaycastHit hit)
    {
        if (hit.collider.name=="ColorChoose")
        {
            clickTexture2D =  hit.collider.gameObject.GetComponent().sprite.texture;
            CaculateVector();
            testColor = clickTexture2D.GetPixel((int)colorPos.x,(int)colorPos.y);
            image.color = testColor;
        }   
    }

    private void CaculateVector()
    {
        colorPos.x = (Input.mousePosition.x - textureOriginScreenPosition.x) / (textureEndUPScreenPosition.x - textureOriginScreenPosition.x) * clickTexture2D.width;
        colorPos.y = (Input.mousePosition.y - textureOriginScreenPosition.y) / (textureEndUPScreenPosition.y - textureOriginScreenPosition.y) * clickTexture2D.height;
        
    }
}
HitColorChooseImage(RaycastHit hit),该方法写入射线检测即可。 主要解决问题是计算鼠标位置的像素的坐标。

你可能感兴趣的:(Unity)