- Home /
Confused with LookRotation in C#
I have a turret I would like to automatically look at specific targets, rotating only on the Z-axis, looking up. Most of the examples I see of LookRotation are in Javascript, which does Quaternions differently than C#. In JS you can list the axes seperately but you can't go that in C#. Example:
public Transform target;
void Update () {
var newRotation = Quaternion.LookRotation(target - transform.position).eulerAngles;
newRotation.x = 0;
newRotation.y = 0;
transform.rotation = Quaternion.Euler(newRotation);
}
Isn't as simple in C#. Quaternions are pretty confusing to me so I was just wondering how to limit the rotation to just Z-axis in C#.
Answer by robertbu · Aug 16, 2013 at 01:46 AM
I believe this is what you are looking for:
public Transform target;
void Update () {
Vector3 look = target.position - transform.position;
look.z = 0;
transform.rotation = Quaternion.LookRotation(look);
}
That gives me the error of:
Operator '-' cannot be applied to operands of type UnityEngine.Transform' and
UnityEngine.Vector3'
That was it, should have noticed that myself lol
It's rotating on the correct axis now but the cannon barrel itself is not pointing at the target. It's a simple object I made in Blender and I just applied the scrip to the barrel. What do I have to do to specify that I want the tip of the barrel itself to look at objects?
Transform.LookAt() and Quaternion.LookRotation() assume that the front of the object is looking towards positive 'Z'. You can use an empty game object with the visible object as a child. The script goes on the empty game object, and you use a local rotation on the child to fix things. But by far the best fix is to go back to blender and change the default rotation so that the gun barrel is pointing to positive 'Z'.
Now that seems to be a whole new bag of headaches lol. It seems as if all the problems I've been having with getting objects to rotate correctly has to do with object orientation in Blender vs. Unity. Guess I have some reading to do. Thanks a bunch!
Your answer
Follow this Question
Related Questions
to rotate along z axis 1 Answer
Quaternion.LookRotation only on Y axis 0 Answers
LookRotation but keeping oriented a certain way 0 Answers
Slerp to make the right/left side face another object 2 Answers