character lookAt on spherical planet - Face Y to Target and XZ to Planet !?

Hi, I’m trying to solve this but unfortunately, can’t find a good solution for this.

My character is standing on a spherical Planet and should always look into the direction of another object, which is moving around on a planet.
This means, his Y rotation should rotate him into the direction of the object and the X and Z rotation should rotate him into the direction of the planet.

What is the best way to do this?


I’m going to assume that you already have code that sets the character’s ‘y’ to align with the planet, and you are only looking for the code to make the character face the correct direction. Given that the characters orientation is arbitrary (i.e. he can be rotated to any angle), the solution is to project the the position to look at onto a mathematical plane that aligns with the character’s ‘y’ and passes through the pivot point of the character. ‘target’ in the script below is the object the character is to look at. Here is a bit of untested code that should do the job:

#pragma strict
var target : Transform;

function Update() {
	var pos = ProjectPointOnPlane(transform.up, transform.position, target.position);
	transform.LookAt(pos, transform.up);

function ProjectPointOnPlane(planeNormal : Vector3 , planePoint : Vector3 , point : Vector3 ) : Vector3 {
	var distance = -Vector3.Dot(planeNormal.normalized, (point - planePoint));
	return point + planeNormal * distance;