Hello there Unity Community,
I’m very new to both Unity and coding (first week) and have been having trouble figuring out how to do something specific.
I’ve been trying to create a script to rotate an object 90 degrees on input. Note I don’t want the object to “snap” to the next angle, it has to rotate to the new angle. The object also has to be able to rotate a full 360 degrees, i.e. if you press your input four times it’s back where it started.
I’ve been searching for a few days as I didn’t want to give up too easily but I’ve been left a little confused what with all the Quaternions, Transform.rotates, Lerps and Mathf.MoveTowardAngles. I don’t know which direction I should be taking.
I had found a code that sort of did what I wanted, however it didn’t account for multiple button presses, so the object would start a new rotation if you pressed your input during the “active frames”.
The very basic code I have so far is as follows:
using UnityEngine;
using System.Collections;
public class Rotator : MonoBehaviour
{
public float speed;
void tiltLeft()
{
transform.Rotate(Vector3.back * Time.deltaTime * speed);
}
void tiltRight()
{
transform.Rotate(Vector3.forward * Time.deltaTime * speed);
}
void Update()
{
if(Input.GetKey(KeyCode.D))
{
tiltLeft ();
}
if(Input.GetKey(KeyCode.A))
{
tiltRight ();
}
}
}
This only rotates the object while you are pressing the button. I’d like to expand it in the most basic way possible to achieve what I want (press button, rotate 90 degrees in relative direction).
The reason I’ve started with this basic code is because I’d like to learn what and how and expand what I know rather than just having a ready-made solution.
Any help or links to relevant tutorials would be much appreciated.
Thanks in advance!