Hello Unity folks,
In my 2D game I have a floating character which is the main player. If the player is floating towards the left it is leaning left till it reaches 45 degrees on the z axis of Rotation. My question is; How can I make it rotate back to start position when key is released?
This is the script to make it lean to 45 degrees in both direction;
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed = 1f;
private Vector3 myRotation;
void Start() {
myRotation = gameObject.transform.rotation.eulerAngles;
}
void Update() {
if(Input.GetKey(KeyCode.D))
transform.position += new Vector3
(speed * Time.deltaTime, 0.0f, 0.0f);
if(Input.GetKey(KeyCode.A))
transform.position -= new Vector3
(speed * Time.deltaTime, 0.0f, 0.0f);
if(Input.GetKey(KeyCode.D)) {
myRotation.z = Mathf.Clamp(myRotation.z - 1f, -45f, 45f);
transform.rotation = Quaternion.Euler(myRotation);
}
if (Input.GetKey (KeyCode.A)) {
myRotation.z = Mathf.Clamp (myRotation.z + 1f, -45f, 45f);
transform.rotation = Quaternion.Euler (myRotation);
}
}
}
I have tried this code to make it return to start position but it looks strange as the player is not returning slowly to its position:
if(Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D)) {
gameObject.transform.rotation = Quaternion.identity;
}