Reputation: 2472
I'm having a play with Google Cardboard. I am sitting in a cockpit and I can look around it with no problem.
Now I want to tilt my cockpit from side to side to give a more realistic feel rather than just being stationary.
So far I have this:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 0.25f;
void Update()
{
Tilter ();
}
void Tilter()
{
if (transform.rotation.z < 5f) {
transform.Rotate (new Vector3 (0f, 0f, speed));
}
if (transform.rotation.z > 5f)
transform.Rotate (new Vector3 (0f, 0f, -speed));
}
}
This starts tilting the cockpit to the left as expected, but once the rotation gets bigger than the value of 5, the cockpit does not rotate the other way, it keeps rotating the same way, instead of the opposite direction.
Upvotes: 0
Views: 277
Reputation: 601
I have not tried this code, but if I understand what you are trying to do, I would suggest to use Mathf.Sin and Time.time to continuously get values in the range of -1 to 1 and then multiply for the rotating range of your cockpit. For example:
using UnityEngine;
using System.Collections;
public class Tilt : MonoBehaviour
{
float speed = 1.0f;
float rotationAngle = 45;
void Update()
{
Tilter ();
}
void Tilter()
{
float rotationZ = rotationAngle * Mathf.Sin(Time.time * speed);
transform.Rotate (new Vector3 (0f, 0f, rotationZ ));
}
}
This example should slowly rotate your cockpit from 0 to 45, then back to 0, then to -45, then back to 0, an so on (again I have not tried it).
You can increase or decrease the value of speed to make the rotation faster or slower.
Upvotes: 2