I have a mesh with an elbow that I want to orient towards the player. However, the elbow’s z-axis is not pointing towards its tip it points out instead, so when I use transform.LookAt(character), it points the z-axis at the character (like it’s supposed to) and ends up in at a weird angle. I want it to align with this transform’s z-axis when it rotate towards the player so that the tip of the “nozzle” is pointed at the player.
I’ve tried various solutions, but I am missing a basic understanding of what I need to do to correct the offset.
Thanks.
The easiest way I can think of, is to make an empty GameObject, that will be the parent of your mesh.
Then, rotate the child (your mesh), so that the part you refer to as “forward”, is in-line with the parent’s transform transform.forward
(positive z axis).
Once you’ve done that, you can simply use transform.LookAt(character)
, but using the parent object’s transform.
If it’s not possible to change the hierarchy, here’s an alternative solution:
First, create an empty parent object, and add your mesh as a child. Then rotate the child so that it faces the transform.forward of the parent, in the scene. Now, attach the following script to the child object (the mesh):
public class RotationCalculation : MonoBehaviour {
public static Quaternion relativeRotation;
void Start() {
// relativeRotation should hold a quaternion that can be used to rotate the mesh, so that it points toward it's transform.forward.
relativeRotation = Quaternion.Inverse(transform.localRotation);
// after setting the static variable, destroy the object and it's parent
GameObject.Destroy(transform.parent.gameObject);
}
}
Now you have a static variable that you can use to rotate your mesh so that it faces it’s transform.forward. So when you want it to point at something, use the following commands:
transform.LookAt(character);
transform.rotation *= RotationCalculation.relativeRotation;