So I’ve got this cube with a face on it rolling about, and I want to change the face texture so that it looks like it’s watching the hero as he moves about.
So I’ve got my array of Texture2D’s (4 total: up, down, left, right) to slip into my face mainTexture, but I need to figure out the angles on this thing.
I can’t quite grasp it, I’d have to use the objects ‘z’ rotation (Since this is a 2D platformer type game), the cubes position, and the hero’s position to get an appropriate angle, but I’m not sure how and not sure how that would work with replacing the images.
Since it’s quite possible I’m not explaining this well (It is rather late here), here’s an example.
EX:
if the cube is lying on it’s right side, and the hero is to it’s right it would be using the eyes upward image (because it’s lying on it’s side).
Okay, so any help you can give would be great, I keep going back to high school geometry making triangles in my head and mucking about with inverse tangetns, but so far nothing fits.
I think this is what you are looking for. First I assume you’ll have a straight-on image as well as up/down/left/right images. To calculate if you want to use the straight on view, calculate the angle between the vector from the face to your object and the normal of the face. If it is below some threshold, then show the straight-on view.
As for the other four, use the DOT product between your vector to your character and the normal of the plane to project the position onto the face and then use the angle betwen up and this projection to decide which image to display.
Here is a bit of code I used for a quick test. Note goIndicator is a small sphere I used to display the projection point on the plane.
using UnityEngine;
using System.Collections;
public class MakeAFace : MonoBehaviour {
public GameObject goPlayer;
public GameObject goIndicator;
void Update() {
CalcTheFace ();
}
void CalcTheFace() {
Vector3 v3ToPlayer = goPlayer.transform.position - transform.position;
v3ToPlayer.Normalize();
float fAngle = Vector3.Angle (v3ToPlayer, -transform.forward);
Debug.Log ("Angle from Normal = "+fAngle);
Vector3 v3Project;
v3Project = v3ToPlayer - Vector3.Dot(v3ToPlayer, -transform.forward) * -transform.forward;
goIndicator.transform.position = transform.position + v3Project;
fAngle = Vector3.Angle (v3Project, transform.up);
Debug.Log ("Angle between orthogonal projection and up= "+fAngle);
}
}
Note I used a plane created by the CreatePlane() editor script found here for my plane. It has an option to produce a vertical plane, but the face I see is the back not forward, so I have to -transform.forward for the normal. Depending on the natural orientation of the plane you are using, you will have to make appropriate transformations for the normal and up vectors.
couldn´t you create two polyplanes for the eyes and translate them?
it would be way faster and simpler then storing and switching textures.
and the calculation of the corect position should be fairly easy too.