I’m needing to rotate a specific axis (down, left, right etc) of object A towards object B’s position, but relative to the rotation of a mutual parent/ancestor object, rather than to a world axis.
This answer helped me solve the first part.
Vector3 direction = objB.position - objA.position;
Quaternion toRotation = Quaternion.FromToRotation(Vector.down, direction);
objA.rotation = toRotation;
Vector.down (negative y) will point at object B, except that the forward (z) axis will always point towards world forward (z). I have tried a lot of different things, but I haven’t been able to crack it.
So how do I modify this to point the specific axis at the vector while keeping the forward (z) axis facing the forward axis of a shared parent/ancestor object? Thanks.
Well, if you need to base it on the rotation of a base object higher up (or at the top?) of the hierarchy, you’ll need information on that, since any given local rotation is relative only to its immediate parent.
For example:
// Returns the Transform at the very top of the hierarchy
Transform GetParent(Transform current)
{
Transform result = current;
if(current.parent != null)
{
result = GetParent(current.parent);
}
return result;
}
Otherwise, you’ll need a stricter definition which would require tags, layers, manual definition or anything similar.
Now, for the resulting rotation, then, you’ll want to do something along the lines of:
// This ensures that A's down points at B's position
Quaternion rotationOffset = Quaternion.AngleAxis(90.0f, Vector3.right);
// Point straight towards B with secondary emphasis on the root's forward vector
// Then, apply offset to align the downward axis instead
objA.rotation = Quaternion.LookRotation(objB.position - objA.position, objRoot.forward) * rotationOffset;
As an alternative, if facing forward is more important than downward facing towards B, implementation is a much simpler:
objA.rotation = Quaternion.LookRotation(objRoot.forward, objA.position - objB.position);