- Home /
Help with rotation code.
Right now I'm using this code to make my sprite look at the character:
var dx = this.transform.position.x - player.transform.position.x;
var dy = this.transform.position.y - player.transform.position.y;
var radians = Mathf.Atan2(dy,dx);
var angle = radians * lookangle/ Mathf.PI;
var rotateZ = Mathf.LerpAngle(this.transform.rotation.z, angle, Time.time);
this.transform.eulerAngles = new Vector3(this.transform.rotation.x, this.transform.rotation.y, rotateZ);
the problem with this is that I don't want my sprite to rotate past 180 degrees because then it appears upside-down. I have code that I use to flip the sprite around however if I set the look angle to 180 it will flip but won't rotate to face the player. I need something where I can set the sprite to rotate 360 degrees but not under 180 until I flip and then I would switch it around so that it will rotate up to 180. If anyone has some better rotation code that would be appreciated (Has to work in 2D though).Thank you!
Answer by flaviusxvii · Sep 07, 2014 at 07:11 PM
this.transform.rotation.z <-- Unless you are a mathematical genius this is not what you expect. That's the z component of a Quaternion. use this.transform.rotation.eulerAngles.z to get the z rotation.
Answer by zharik86 · Sep 07, 2014 at 06:54 PM
Your problem consists that you misunderstand Quaternion. See docs. Quaternion is the four-component vector which each value is in the range from 0 to 1. And eulerAngles is the three-component vector which each value is in the range from 0 to 360. So, to rotate, to use Quaternion.Euler() better:
private var rotateZ: float = 0.0; //create global variable for save current rotation
function myFunc() { //or maybe this code in function Update()
var dx = this.transform.position.x - player.transform.position.x;
var dy = this.transform.position.y - player.transform.position.y;
var radians = Mathf.Atan2(dy,dx);
var angle = radians * 180.0/ Mathf.PI; //I dont't know what is variable lookangle, but maybe you want translate radians to degree
rotateZ = Mathf.LerpAngle(rotateZ, angle, 5.0*Time.deltaTime);
this.transform.rotation = Quaternion.Euler(0, 0, rotateZ);
}
I hope that it will help you.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162522im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Rotating a model with increments 1 Answer
Smoothing eulerAngles rotation? 1 Answer
How do I call a function containing a while loop, inside the update function? 2 Answers
Rotation on Android vs. PC 0 Answers
Is 360° the same as 0°? 2 Answers