- Home /
Change UV Offset according to target objects to achieve a "Look At" effect
I am currently working on a project that has humanoid models with 2d eye textures like in anime. I have made an eye shader that change the UV offsets using a slider to change the position of iris in the eye texture. But I want the eye texture to automatically change its offsets according the position of any target object. for eg, If a target object is to the eyes' right side, the eye texture should change the offset of its uv in such a way that the iris point towards the target object on the right. I want to emulate something similar to this (reference) - https://www.benjones.us/twilight-princess-eyes-breakdown/
Answer by BastianUrbach · Mar 07 at 09:51 AM
One way of doing this is to trace a ray from the target object to the center of the eye. This gives you the texture coordinates where the pupil should be.
The example below assumes that the pupil is at the center of the texture and that the script is on an object at the (theoretical) center of the eye (the eye geometry might be almost flat in this style but you still need to think about where the center would be if it was spherical). Note that RaycastHit.textureCoord only works on MeshColliders with Convex disabled.
using UnityEngine;
public class EyeLookAt : MonoBehaviour {
public Transform target;
public MeshCollider eyeCollider;
public Material material;
void Update() {
var ray = new Ray(target.position, transform.position - target.position);
if (eyeCollider.Raycast(ray, out var hit, Mathf.Infinity)) {
material.SetTextureOffset("_MainTex", new Vector2(0.5f, 0.5f) - hit.textureCoord);
}
}
}
Thanks a lot! I had tried innumerous methods using raycasts and the coordinate system that eventually failed. Even the web search had limited resources on this. I truly appreciate your help and of the unity community that assist me to learn.