this is my code. I want to rotate the object in this way: press a buttom and the object rotate in the given axis but thre is a problem. when I rotate it in both Y and X it unwantedly rotates in z too I cant find any reason for this (I want something like rotating a first person camera but in this way) here is my code
using UnityEngine;
using System.Collections;
public class sss : MonoBehaviour {
public float turnSpeed = 90;
void Update () {
if (Input.GetKeyDown(KeyCode.LeftArrow))
transform.Rotate(Vector3.up, -turnSpeed, Space.World);
if (Input.GetKeyDown(KeyCode.RightArrow))
transform.Rotate(Vector3.up, turnSpeed, Space.World);
if (Input.GetKeyDown(KeyCode.UpArrow))
transform.Rotate(Vector3.right, turnSpeed, Space.World);
if (Input.GetKeyDown(KeyCode.DownArrow))
transform.Rotate(Vector3.right, -turnSpeed, Space.World);
}
}
If you don’t ever need it to move on the Z axis, you could always put a RigidBody component on the GameObject and freeze rotation along the Z axis.
Your code is correct but you’re actually rotating it freely in all directions:
private float velocityX, velocityY;
public float maxX = 90f;
public float maxY = 45f;
public float turnSpeed = 3f;
void Update () {
if(Input.GetKeyDown (KeyCode.LeftArrow)) {
velocityX += turnSpeed;
}
if(Input.GetKeyDown (KeyCode.RightArrow)) {
velocityX -= turnSpeed;
}
if(Input.GetKeyDown (KeyCode.UpArrow)) {
velocityY -= turnSpeed;
}
if(Input.GetKeyDown (KeyCode.DownArrow)) {
velocityY += turnSpeed;
}
//clamp values
if (velocityX > 360) {
velocityX -= 360;
}
if (velocityX < -360) {
velocityX += 360;
}
if (velocityY > 360) {
velocityY -= 360;
}
if (velocityY < -360) {
velocityY += 360;
}
velocityX = Mathf.Clamp (velocityX, -maxX, maxX);
velocityY = Mathf.Clamp (velocityY, -maxY, maxY);
transform.rotation = Quaternion.Euler (velocityY, velocityX, 0);
}