C#

C# code
mail@pastecode.io avatar
unknown
abc
3 years ago
2.0 kB
1
Indexable
Never
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SampleTest : MonoBehaviour
{
    public Texture2D texture;
    public Material m_Material;

 
    public float worldSize;
    public string textureName = "_MainTex";

 
    public Vector3 currentPos;
    public Vector2 currenUv;
    public Vector4 value;
    public Color colorValue;
    public Vector3 LeftDownPosition
    {
        get
        {
            Vector3 left = transform.position;
            left.x -= worldSize * 0.5f;
            left.z -= worldSize * 0.5f;
            return left;
        }
    }
    private void Update()
    {
        if (m_Material && texture)
        {
            m_Material.SetTexture("_MainTex", texture);
            if (Input.GetMouseButton(0))
            {
                var mousePos = Input.mousePosition;
                Ray ray = Camera.main.ScreenPointToRay(mousePos);
                Plane plane = new Plane(Vector3.up, Vector3.zero);
                plane.Raycast(ray, out var enter);
                currentPos = ray.GetPoint(enter);
                currenUv = GetUv(currentPos);
            }
            value = colorValue = texture.GetPixelBilinear(currenUv.x, currenUv.y);
        }

    }
 

    float Remap(float value, float From1, float To1, float From2, float To2)
    {
        return From2 + (value - From1) * (To2 - From2) / (To1 - From1);
    }

    public Vector2 GetUv(Vector3 worldPos)
    {
        var origin = LeftDownPosition;

        float u = Remap(worldPos.x, origin.x, origin.x + worldSize, 0f, 1f);
        float v = Remap(worldPos.z, origin.z, origin.z + worldSize, 0f, 1f);
        return new Vector2(u, v);
    }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(currentPos,5f);
        Gizmos.DrawWireCube(transform.position, Vector3.one * worldSize - Vector3.up * worldSize);
    }

}