Reputation: 111
I want to rotate a cube in Unity3D.When I push arrow left button on keyboard the cube have to rotate left.If I push up, the cube have to rotate up.But with my script the cube rotate left and then the left-side rotate up.
This is the current status:
That's what I want:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rotate : MonoBehaviour
{
public float smooth = 1f;
private Quaternion targetRotation;
// Start is called before the first frame update
void Start()
{
targetRotation = transform.rotation;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.UpArrow)){
targetRotation *= Quaternion.AngleAxis(90, Vector3.right);
}
if(Input.GetKeyDown(KeyCode.DownArrow)){
targetRotation *= Quaternion.AngleAxis(90, Vector3.left);
}
if(Input.GetKeyDown(KeyCode.LeftArrow)){
targetRotation *= Quaternion.AngleAxis(90, Vector3.up);
}
if(Input.GetKeyDown(KeyCode.RightArrow)){
targetRotation *= Quaternion.AngleAxis(90, Vector3.down);
}
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10* smooth * Time.deltaTime);
}
}
Upvotes: 1
Views: 1584
Reputation: 20270
The way you have it now, the rotations are applied to the axes as they would be after the original rotation because you are effectively doing targetRotation = targetRotation * ...;
.
However, you want to rotate the rotation around the world axes. You can do this by doing targetRotation = ... * targetRotation;
:
void Update()
{
if(Input.GetKeyDown(KeyCode.UpArrow)){
targetRotation = Quaternion.AngleAxis(90, Vector3.right) * targetRotation;
}
if(Input.GetKeyDown(KeyCode.DownArrow)){
targetRotation = Quaternion.AngleAxis(90, Vector3.left) * targetRotation;
}
if(Input.GetKeyDown(KeyCode.LeftArrow)){
targetRotation = Quaternion.AngleAxis(90, Vector3.up) * targetRotation;
}
if(Input.GetKeyDown(KeyCode.RightArrow)){
targetRotation = Quaternion.AngleAxis(90, Vector3.down) * targetRotation;
}
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 10* smooth * Time.deltaTime);
}
See How do I rotate a Quaternion with 2nd Quaternion on its local or world axes without using transform.Rotate? for more information.
Upvotes: 1