- Home /
Question by
UnityGISTech · May 29, 2017 at 06:35 AM ·
heightmapelevation
How to Read Elevation from Heightmap
Hi Guys anyone can help me to use correctly "GetPixel" and "ReadPixel" to real the real elevation from heightmap when clicking on mouse plz. i tryed this code : using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GetValue : MonoBehaviour {
public Vector3 size = new Vector3(100, 10, 100);
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit hit = new RaycastHit();
Ray ray = new Ray();
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(0))
{
// Debug.Log("mouse down");
if (Physics.Raycast(ray, out hit))
{
Vector3 hitPos = Camera.main.WorldToScreenPoint(hit.point);
//Debug.Log(hitPos + " - " + hit.collider.name);
MeshRenderer rend = hit.collider.GetComponent<MeshRenderer>();
//Texture to Texture2D
Texture mainTexture = rend.material.mainTexture;
Texture2D texture2D = new Texture2D(mainTexture.width, mainTexture.height, TextureFormat.RGBA32, false);
RenderTexture currentRT = RenderTexture.active;
RenderTexture renderTexture = new RenderTexture(mainTexture.width, mainTexture.height, 32);
Graphics.Blit(mainTexture, renderTexture);
RenderTexture.active = renderTexture;
texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.Apply();
Color[] pixels = texture2D.GetPixels();
RenderTexture.active = currentRT;
/////
Vector2 pixelUV = hit.textureCoord;
float uvX = pixelUV.x * texture2D.width;
float uvY = pixelUV.y * texture2D.height;
Color hitColor = texture2D.GetPixel((int)uvX,(int) uvY);
Debug.Log(hitColor + " " + uvX + " " + uvY);
Vector3 pos = hitPos;
int x = Mathf.FloorToInt(hitPos.x / size.x * texture2D.width);
int z = Mathf.FloorToInt(hitPos.z / size.z * texture2D.height);
pos.y = texture2D.GetPixel(x, z).grayscale;
}
}
}
}
result:
RGBA(0.161, 0.161, 0.161, 1.000) 777.5255 438.3657
Comment