This is a bit of a specific one so bear with me.
I have a game with Rigidbody2D-based characters. It’s side view, and characters can float/swim around X/Y axes freely.
My NPCs are 3D meshes, so they can be rotated to look in the direction of their movement. I have the mesh as a child of an empty gameobject which I can use for this purpose.
The problem is that I want their rotation to be limited to a narrower cone, so they’re not facing absolutely in that direction, but kind of half-facing the camera so you can see their faces.
See this image above. The character can move along X and Y, but they should not have free rotation. It should be clamped to a circle kind of like the green cone (same angle in all directions).
The result should be that they always look kind of like one of the blue faces in the image on the right, always half-facing the camera and half-facing their direction of movement.
I’m struggling to figure out the maths required to get this effect. I’ve got something approximately working but it’s not smooth and it’s not accurate.
void LookTowardsTarget(Vector3 target)
{
Vector3 direction = (lastLightPosition - transform.position).normalized;
float clampedX = direction.x * maxPivotAngle;
float clampedY = direction.y * maxPivotAngle;
if (direction.x < 0 && clampedY < 0)
clampedY = -clampedY;
else if (direction.x > 0 && clampedY < 0)
clampedX = -clampedX;
else if (direction.x > 0 && clampedY > 0)
clampedY = -clampedY;
else if (direction.x < 0 && clampedY > 0)
clampedX = -clampedX;
lookPivot.rotation = Quaternion.Euler(clampedX, clampedY, 0f);
}
The 4 “if” statements are there to correct and negate certain axes being negative or positive in the code that precedes it. I’m happy to throw all this away though.
Uhh… help?! Rotational mathematics are really not my strong point!