- Home /
Rotate on one axis
I was wondering how I can restrict the following code to rotate around the z axis only?
Quaternion targetRotation = Quaternion.LookRotation(target.position - turret.transform.position, Vector3.up);
turret.transform.rotation = Quaternion.Slerp(turret.transform.rotation, targetRotation, Time.deltaTime * 2.0f);
I'm working on a top down game so I only want it to rotate around one axis to face the player. Can it be done the way im trying above?
Thanks
Answer by Statement · Jan 13, 2011 at 12:35 PM
You could try setting the look direction z to zero. I created a temporary variable to illustrate this easier.
var lookDirection = target.position - turret.transform.position; lookDirection.z = 0;
var targetRotation = Quaternion.LookRotation(lookDirection, Vector3.up); turret.transform.rotation = Quaternion.Slerp(turret.transform.rotation, targetRotation, Time.deltaTime * 2.0f);
I haven't tested this but it should be easy enough to test this for you with 2 more lines of code.
If you are getting dodgy results, try normalizing lookDirection after modifying z.
I fooled around with the code you posted and I'm still having trouble. I checked out my turrets orientation. The turrent sprite faces downward and the upwards y direction faces upward for it, so in the opposite direction.
I fooled around with setting each value individually the 0 for x, y, z.
I'm guessing I only want to rotate on the y axis so I tried setting the z and x to zero. But what happens is it rotates on the x as the player gets closer to in the top down view it appears to flip.
This is really hard to explain :(
When I try the following var lookDirection = target.position - turret.transform.position; Quaternion targetRotation = Quaternion.LookRotation(lookDirection, Vector3.down); turret.transform.rotation = Quaternion.Slerp(turret.transform.rotation, targetRotation, Time.deltaTime * 2.0f);
The turrets x forward tries to face the target. Which is the bottom of the sprite.
Sorry to comment on an old thread, but I noticed the top line is javascript and the 3rd is C#. (Unless you are using var type inference, which you and I understand, but many people would never figure out :) )
Answer by Rally Raghavan · Mar 13, 2011 at 08:59 PM
Quaternion rotation = Quaternion.LookRotation(rotation, Vector3.up);
This line in the code shows some semicolon error. I do not understand what error it is. Error says, there should be a semicolon in the end.
Remove "Quaternion" at the beginning of the line and replace it with "var".
ya i tried it already. says some different error then. Assets/Codes/boatForce.js(17,67): BCE0023: No appropriate version of 'UnityEngine.Quaternion.LookRotation' for the argument list '(UnityEngine.Quaternion, UnityEngine.Vector3)' was found. This is the error that pops out.
Quaternion.LookRotation(Vector3 dir, Vector3 up). You have to pass 2 Vector3's as an argument.
Your answer