- Home /
Saving Rotation of Sprite
Hello programmers who are better than me! I have this code, which is working beautifully at facing my sprite in whichever direction it is moving. The problem is that when it stops moving the sprite locks back to its initial rotation, when I would like it to stay at the rotation it was at just before stopping. How can I achieve this? Many thanks.
using UnityEngine;
using System.Collections;
public class FaceDirection : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector2 moveDirection = gameObject.GetComponent<Rigidbody2D>().velocity;
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
Answer by zach-r-d · Aug 10, 2015 at 03:07 AM
Try checking if the magnitude of moveDirection is above a small threshold before changing the rotation:
Vector2 moveDirection = gameObject.GetComponent<Rigidbody2D>().velocity;
if (moveDirection.magnitude > .01f) {
float angle = Mathf.Atan2(moveDirection.y, moveDirection.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
Hmm..... That makes total sense and it should work, but it still does the same thing. Thank you so much for your efforts! There are no compiler errors or anything, it just snaps back to the initial rotation when it stops moving.
Is there any other script that affects the rotation of the object?
$$anonymous$$ay I ask why is this happening? I have the same problem with him above and it worked for me thank you for your answer! :D
Your answer
Follow this Question
Related Questions
Why the player is not rotating and moving at the same time ? 0 Answers
Flip over an object (smooth transition) 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
How to rotate a tank turret and gun? 2 Answers
GetKeyUp not registering 2 Answers