How to access y rotation of an object as a variable or value
So, after many unsuccessful attempts, I've failed to put limitations on how far my camera can rotate. My query; I want to access the y variable of the transform and use the number given to turn a bool on and off.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateCam : MonoBehaviour {
public static bool GreaterThen;
public static bool LessThen;
public Vector3 yValhue;
void Start(){
GreaterThen = false;
LessThen = false;
}
void Update () {
yValhue = Vector3 (0, transform.rotation, 0);
if (GreaterThen == false) {
if (Input.GetKeyDown (KeyCode.LeftArrow)) {
transform.RotateAround (Vector3.zero, Vector3.up, 300 * Time.deltaTime * 2);
if (yValhue = 30) {
Debug.Log("Oh jeez I guess greater then is off");
}
}
}
if(LessThen == false){
if (Input.GetKeyDown (KeyCode.RightArrow)) {
transform.RotateAround (Vector3.zero, Vector3.down, 300 * Time.deltaTime * 2);
//if (yValhue = 30.0) {
Debug.Log ("Wow! You're not a big fool after all! Less then ain't runnin' no more.");
}
//}
}
}
}
I know, I know. I'm definitely new. I ONLY want to set limits on the rotation of the Y axis. Why is it so hard?? I am but a simple boy please have mercy C# gods-
But anyways, thank you in advance.
Answer by UnityCoach · Oct 18, 2018 at 07:54 AM
Hi, we've all been there once.
Vector3 is a struct, hence a value type. You cannot assign a struct component directly. If you did something like :
transform.position.x += 10;
Unity would through an error and give you a hint such as "consider storing the value..". You need to do something like :
Vector3 p = transform.position;
p.x += 10;
transform.position = p;
So, you can create a property to access eulerAngles (rotations are Quaternions), and limit it Y value.
Vector3 eulerAngles
{
get { return transform.eulerAngles; }
set
{
transform.eulerAngles = new Vector3 (value.x, Mathf.Clamp(value.y, min, max), value.z);
}
}
Hope this helps.
In your case, you could also simply check for the Y component before you Rotate the object.
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftArrow) && transform.eulerAngles.y > -30f)
RotateAround ([...])
else (Input.Get$$anonymous$$ey($$anonymous$$eyCode.RightArrow) && transform.eulerAngles.y < 30f)
RotateAround ([...])
Dude sorry for the late reply but THAN$$anonymous$$ YOU SO $$anonymous$$UCH $$anonymous$$AN it really means a lot and my god man i'd been trying to get over that hill for weeks-
No problem, like I said, we all struggle with something at some point. Please accept the answer to close the question if that works for you. Cheers.