- Home /
Rotation being forced away from what I want
So I have a script for character movement. I have a script that forces the character to face the direction of movement. Problem is for my character, I need the rotation to be X: 90, Y, 180.
Here is my script. It works fine for what I want to do above, but it forces the X and Y rotation to 0. How do I fix this?
private GameObject parent;
private Vector3 dir;
void Start(){
parent = transform.parent.gameObject; //The object uses its parent's velocity
}
void Update () {
Vector2 dir = transform.parent.rigidbody2D.velocity;
float angle = Mathf.Atan2(-dir.y, -dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
Answer by Scribe · Apr 19, 2016 at 09:30 AM
Option 1 (easy option): set your object to the child of something else, and then rotate the parent around the z direction.
Option 2: Save your desired rotation in a variable and apply your rotation around z as an additional rotation.
Quaternion initialRot;
void Start(){
initialRot = this.transform.rotation; //or possibly Quaternion.Euler(blah blah)
}
void Update(){
transform.rotation = initialRot*Quaternion.AngleAxis...;
}
It is possible that for this, you may need to convert Vector3.forward into local space before rotating around it, see Transform.InverseTransformDirection.
I ended up using both options as it was the only way Unity would allow it to work. I parented it to an object with an X-Y rotation of 90-180 and used initialRot as suggested to get it to work. Still had to monkey around with (-dir.y, -dir.x) part and had to change the Vector3 to Up, but it works now. Thank you!
Your answer
Follow this Question
Related Questions
(s)lerp y-rotation to the direction of velocity 0 Answers
Modify rotation based on passing rigidbody's velocity and direction? 1 Answer
Gun not firing in certain direction 1 Answer
Objects Rotation to modify Objects transform velocity/Direction of travel 1 Answer
Teleport and change direction of current velocity. 2 Answers