Using the trick discussed in a similar question here and also here, we can define a helper method to point our local Y axis exactly in a particular direction, while turning our local Z axis to face (as close as possible) toward another direction.
Quaternion TurretLookRotation(Vector3 approximateForward, Vector3 exactUp)
{
Quaternion rotateZToUp = Quaternion.LookRotation(exactUp, -approximateForward);
Quaternion rotateYToZ = Quaternion.Euler(90f, 0f, 0f);
return rotateZToUp * rotateYToZ;
}
Now we can use that in Update to face toward our target:
void Update() {
// Form the direction we want to look towards
Vector3 offsetToTarget = target.position - transform.position;
// Preserve our current up direction
// (or you could calculate this as the direction away from the planet's center)
Vector3 up = transform.up;
// Form a rotation facing the desired direction while keeping our
// local up vector exactly matching the current up direction.
Quaternion desiredOrientation = TurretLookRotation(offsetToTarget, up);
// Move toward that rotation at a controlled, even speed regardless of framerate.
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
desiredOrientation,
maxDegreesPerSecond * Time.deltaTime
);
}
I found something interesting: when I reduce the speed of the rotation, the problem disapear, when I have a fast speed, for non perpendicular case, the movement is smooth and fast, and when i'm perdendicular, the rotation is instant. Weird
– Ugo Hed Feb 02 '19 at 17:29maxDegreesPerSecond
speeds. The sudden snap might be coming from the code you're using to turn the object to match its new surface. I recommend posting a new Question containing a minimal, complete, verifiable example of all the code needed to reproduce the problem. – DMGregory Feb 02 '19 at 18:24Transform rotateEmpty
, and then with myQuaternion desiredOrientation = TurretLookRotation(offsetToTarget, up);
, I set to my empty object the desired rotation:rotateEmpty.rotation = desiredOrientation
, and then I get my final Vector3 withVector3 desiredVectorOrientation = rotateEmpty.forward.
Do you know a way to get this vector without an empty object ? thanks
– Ugo Hed Mar 31 '19 at 11:46Vector3 desiredForward = desiredOrientation * Vector3.forward
though. – DMGregory Mar 31 '19 at 11:50