So I am trying to make my character smoothly rotate around when he changes direction in my sidescrolling game. I read up on it and I thought I would have it working 100% but I am running into a weird issue. Basically you start off facing right and if you press left your character will rotate around smoothly and then once he is fully rotated to 0 y rotation, he starts to run. then if you press right he is Supposed to rotate around the opposite direction until he reaches 180 rotation and then he will start to run right. However the issue is instead of this he rotates to “179.3634” y and will not ever complete his rotation.
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour {
//speed of player
public int speed = 1;
//turn rate
public float turningRate = 1F;
//no rotation
private Quaternion zeroRotate = Quaternion.identity;
//rotation y = 180
private Quaternion OneEightyRotation = new Quaternion(0,180,0,1);
// Use this for initialization
void Start ()
{
//set initial rottation (facing right)
transform.eulerAngles = new Vector3(0, 180, 0);
}
// Update is called once per frame
void Update ()
{
//if user is pressing left or right or w or a
if (Input.GetAxis("Horizontal") != 0)
{
//takes input * time * speed to get our movement
var movement = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
//if the movment is negative aka go left
if (movement < 0)
{
//if the current angle is set to 0 (so the player doesnt mess around with their z value)
if (transform.rotation.eulerAngles.y == 0)
{
//move the player movement in the x direction
transform.Translate(movement, 0, 0);
}
else
{
//if the rotation is not 0, then we rotate towrds that rotation (0,0,0,1) from above with respect to delta time & turningRate
transform.rotation = Quaternion.RotateTowards(transform.rotation, zeroRotate, turningRate * Time.deltaTime);
}
}
//if hte movement is > 0 aka the player is going right
else
{
//same check as before but this time to see if the player is rotated to y = 180 degrees
if (transform.rotation.eulerAngles.y == 180)
{
//if so move them -movement in the x direction
transform.Translate(-movement, 0, 0);
}
else
{
//if the rotation is not 180 then we rotate towards that rotation (0,180,0,1) from above with respect to delta time & turnrate
transform.rotation = Quaternion.RotateTowards(transform.rotation, OneEightyRotation, turningRate * Time.deltaTime);
}
}
}
else
{
//do nthing yet (when player is not pressing directional key)
}
}
}