- Home /
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?
TIA
Answer by robertbu · Feb 24, 2014 at 01:50 AM
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 {
planeNormal.Normalize();
var distance = -Vector3.Dot(planeNormal.normalized, (point - planePoint));
return point + planeNormal * distance;
}
Do you also have an advice to lerp the Y rotation to get a smooth rotation? I'm using transform.rotation = Quaternion.FromToRotation (Vector3.up, dir2Planet); to align the player to the planet. Unfortunately, the Y Rotation is always completely off after that, which stops me from simply lerping it.
I'll assume that 'planet' is the transform of the planet. You could do:
transform.rotation = Quaternion.FromToRotation(transform.up, transform.position - planet.position) * transform.rotation;
If you want to Slerp it, you can do:
var rotation = Quaternion.FromToRotation(transform.up, transform.position - planet.position) * transform.rotation;
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * speed);
$$anonymous$$an, you're an absolute genious. I've been looking for a solution to the problem for over 2 weeks now and stumbled across your answer. Works perfectly. You're the best, I really appreciate you sharing the information :D.
Your answer
![](https://koobas.hobune.stream/wayback/20220613134516im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Align transform Y axis to -Physics.gravity 1 Answer
changing transform of an object (without using "look at") 2 Answers
How to move a planar object around a sphere? 2 Answers
Mega Bug In Turret - Help 5 Answers
rotate on the Y axis 1 Answer