Rotate a GameObject a fixed amount on key press struggles. Stops at 180.
I've created an object that I want to rotate a set number of degrees every time the player presses a button, in this case 'd'. I was hoping to have one script that would work regardless of what the angle is. I'm just a hobbyist and I'm self taught, but this is the first thing I've tried to do that hasn't worked and I haven't been able to find anything that really explains what's going on.
Everything is working beautifully, except it a) stops rotating once it's hit 180 degrees and b) even with the Mathf.Round I'm still ending up with decimal values in the Z-axis after rotation, but since I'm only ever going to be rotating nice even numbers I would like it to keep to whole numbers so it is consistent and doesn't stray a few degrees left or right of centre.
What am I doing wrong? Do I just need to add an if x > 180 type statement in there somewhere? that would be easy enough but doesn't seem like the best way of going it.
Or if there is a better way of approaching this, please point me in the right direction if possible. I'll paste my code in below. Any insight would be much appreciated! Grasping rotations, Quaternions and Euler angles has been the most challenging thing so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour {
public int numberOfItems;
public float angleToRotate;
public Quaternion targetRotation, currentRotation;
public bool isMoving;
void Start () {
angleToRotate = 360 / (float)numberOfItems;
}
void Update () {
if (!isMoving) {
if (Input.GetKeyDown (KeyCode.D)) {
StartCoroutine (MenuNext ());
}
}
}
public IEnumerator MenuNext () {
isMoving = true;
targetRotation = transform.rotation * Quaternion.Euler (0, 0, angleToRotate);
currentRotation = transform.rotation;
while (currentRotation.z < targetRotation.z) {
transform.RotateAround (transform.position, Vector3.forward, Mathf.Round(2 * angleToRotate * Time.deltaTime));
currentRotation = transform.rotation;
yield return null;
}
isMoving = false;
}
}
Answer by DWmDM · Aug 01, 2017 at 12:06 AM
Posted a video to YouTube showing the full thing running and stopping at 180. It might also explain why the angle to rotate is calculated the way it is (which could be incorrectly!)
Your answer
Follow this Question
Related Questions
Questions about Rotations in unity 1 Answer
Camera X Rotation Problems 0 Answers
Assign an object rotation along a single axis from other object's rotation. 0 Answers
Something seriously weird is going on with my transform.eulerAngles 0 Answers
How to have objects rotate around a given point that are scripted to face the player 1 Answer