What code would I need to rotate an object on the Z axis say 45 degrees when the player moves the object to the right and -45 degrees when he moves it to the left and back to 0 degrees when the player is not moving the object at all. I have to code to move the object left and right using transform.translate and using the raw axis value. I think I need to do something with Quaternians checking if the object is moving right or left and then rotating over time using time.deltaTime. Any help would be appreciated. Thanks!
You said that you were suing Input.GetAxisRaw why do you not just check if the object is moving left or right using them? I will give you and example.
function Update (){
//Moving right(I believe).
if(Input.GetAxisRaw > 0.1){
transform.Rotation.y += 45 * Time.deltaTime;
}
//Moving left.
else if(Input.GetAxisRaw < -0.1){
transform.Rotation.y -= 45 * Time.deltaTime;
}
}
Are you not following? Just ask.
Here is what I have now. It works for rotating the object left and right but I can’t get it to rotate the object back to 0 when the player isn’t moving the object, ie when GetAxisRaw = 0. I need to rotate the object to angle 0 on the z axis when GetAxisRaw is 0.
void Update()
{
transform.Translate(Input.GetAxisRaw("Horizontal")* Time.deltaTime * playerSpeed,0,
Input.GetAxisRaw("Vertical") * Time.deltaTime * playerSpeed, Space.World);
//Moving right.
if(Input.GetAxisRaw("Horizontal") > 0 && transform.rotation.z > -.15)
{
transform.Rotate(0,0,-5 * Time.deltaTime* rotateSpeed);
}
//Moving left.
else if(Input.GetAxisRaw("Horizontal") < 0 && transform.rotation.z < .15)
{
transform.Rotate(0,0,5 * Time.deltaTime * rotateSpeed);
}
//if(Input.GetAxisRaw("Horizontal") == 0 && transform.rotation.z != 0)
//{
// transform.Rotate(0,0,1 * Time.deltaTime * rotateSpeed);
//}
//Debug.Log (transform.rotation.z);
}
I got it working now. I added the following to get it rotate back to 0.
if(Input.GetAxisRaw("Horizontal") == 0 && transform.rotation.z != 0)
{
transform.rotation = Quaternion.Lerp (transform.rotation,
Quaternion.identity, Time.deltaTime * 10);
}