Reputation: 145
I am able to rotate a cube in multiple directions using this code :
public float speed = 100f;
public Animation anim;
Animator animator;
public Vector3 RotateAmount;
bool running = false;
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
if (Input.GetKey("up"))
transform.Rotate(Vector3.right, speed);
if (Input.GetKey("left"))
transform.Rotate(Vector3.up, speed);
if (Input.GetKey("right"))
transform.Rotate(Vector3.down, speed);
if (Input.GetKey("down"))
transform.Rotate(Vector3.left, speed);
}
Now what i want is to rotate a cube no matter which face is in front. But above code does not do that.If i press a then it rotates right but then when i press right it rotates left. This is what i want to avoid. Can someone help me in figuring out the logic or any idea?
Beginner with unity pls.
Upvotes: 2
Views: 3794
Reputation: 982
You should multiply speed
with Time.deltaTime
else your rotation speed will be dependent on the current framerate.
You are probably adding rotation in local space which messes everything up.
RotateScript.cs
using UnityEngine;
public class RotateScript : MonoBehaviour
{
float speed = 100f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey("up"))
{
transform.RotateAround(this.transform.position, new Vector3(1, 0, 0), speed * Time.deltaTime);
}
if (Input.GetKey("down"))
{
transform.RotateAround(this.transform.position, new Vector3(-1, 0, 0), speed * Time.deltaTime);
}
if (Input.GetKey("left"))
{
transform.RotateAround(this.transform.position, new Vector3(0, 1, 0), speed * Time.deltaTime);
}
if (Input.GetKey("right"))
{
transform.RotateAround(this.transform.position, new Vector3(0, -1, 0), speed * Time.deltaTime);
}
}
}
This code is rotating the cube around its current position in the world this.transform.position
(If you use a different model make sure this point is the center of the object, else the rotation will look weird).
In the case of objects that are not modelled with the origin as center you can try transform.renderer.bounds.center
to get the center.
Upvotes: 3