- Home /
,The object rotates in z axis unwantedly
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);
}
}
Answer by MohammadAlizadeh · May 02, 2018 at 11:16 AM
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);
}
thanks. but I dont want to use mouse..$$anonymous$$eyboard Only.could you give me a new code?
Answer by stardust-system · May 01, 2018 at 09:10 PM
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 answer
Follow this Question
Related Questions
How to stop rotation in x and y axis??? 2 Answers
How to rotate object slowly on only Z axis 2 Answers
Rotation question 1 Answer
Set rotation based on 2 points problem 1 Answer
Sprite rotation (z-axis) and translation (y) is not working 1 Answer