The cube (see left in the screenshot below) should get the color of a video texture mapped to a geometry at click position. But the cube gets a wrong color. The code is attached below (+ Unitypackage). There must be something wrong with mapping the x/y coordinates. I tried lots of things to solve the coords mapping issue, eg. using RaycastHit,textureCoord (see https://docs.unity3d.com/ScriptReference/RaycastHit.textureCoord.html).
However, I was not able to fix the issue. Maybe it´s because I did´t really understand how to use RacastHit.textureCoords in this case, but I think this might be what I need to pick the exact color out of the video.
Maybe you can help me?
using UnityEngine;
using System.Collections;
public class webcam : MonoBehaviour {
public WebCamTexture wct;
public GameObject cube;
void Start () {
wct = new WebCamTexture ();
GetComponent<Renderer> ().material.mainTexture = wct;
wct.Play ();
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit = new RaycastHit ();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit)){
Debug.Log ("Click position: " + hit.point);
Color color = wct.GetPixel ((int)hit.textureCoord.x, (int)hit.textureCoord.y);
Debug.Log ("Color x/y: " + color);
cube.GetComponent<Renderer> ().material.color = color;
}
}
}
}
[81060-videocolorpicker-2unitypackage.zip|81060]
EDIT:
When I try to integrate Recast.textureCoord to the code above, the color of the cube on the left does not change any more at all. Instead Unity tells me “Object reference not set to an instance of an object.”
I wonder why.
Line 31 is:
pixelUV.x *= tex.width;
Here what I did (which does not work for me):
using UnityEngine;
using System.Collections;
public class newColorPicker : MonoBehaviour {
Camera cam;
public GameObject cube;
public WebCamTexture wct;
public GameObject textureScreen;
void Start(){
cam = Camera.main;
wct = new WebCamTexture ();
GetComponent<Renderer> ().material.mainTexture = wct;
wct.Play ();
}
void Update() {
if (Input.GetMouseButtonDown (0)) {
RaycastHit hit = new RaycastHit ();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit) && hit.transform.gameObject == textureScreen) {
Renderer rend = hit.transform.GetComponent<Renderer> ();
MeshCollider meshCollider = hit.collider as MeshCollider;
Vector3 screenPos = cam.WorldToScreenPoint(hit.point);
Vector2 screenRatio = new Vector2(screenPos.x / Screen.width, screenPos.y / Screen.height);
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width; // Line 31 - error at this line
pixelUV.y *= tex.height;
Debug.Log ("pixelUV.x: " + pixelUV.x);
Color color = wct.GetPixel ((int)(screenRatio.x * pixelUV.x), (int)(screenRatio.y * pixelUV.y));
Debug.Log ("Color x/y: " + color);
cube.GetComponent<Renderer> ().material.color = color;
}
}
}
}