本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一个小功能的示例程序,目的是通过鼠标点击图片后,拾取图片上鼠标位置处的颜色。
本示例用图:
效果(左侧方块为拾取的颜色)
功能代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class _1ColorCheck : MonoBehaviour
{
public Image displayImg;
public Sprite palette;
Vector2 pltSize;
// Start is called before the first frame update
void Start()
{
pltSize = new Vector2(palette.rect.width, palette.rect.height);
}
Ray ray;
RaycastHit hit;
Vector3 hitPoint;
Vector2 texPos = new Vector2();
float x;
float y;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100))
{
hitPoint = hit.transform.InverseTransformPoint(hit.point);
texPos = (Vector2)hitPoint + hit.transform.GetComponent<RectTransform>().sizeDelta / 2f;
x = texPos.x / hit.transform.GetComponent<RectTransform>().sizeDelta.x * pltSize.x;
y = texPos.y / hit.transform.GetComponent<RectTransform>().sizeDelta.y * pltSize.y;
Debug.Log("x: " + x + ", y: " + y);
displayImg.color = palette.texture.GetPixel((int)x, (int)y);
}
}
}
}
测试方法,将脚本挂在场景对象上,创建两个Image,其中displayImg显示鼠标拾取后的颜色,palette为画板。