I am stuck with a little problem.
I have made a 3D cube and set up the GoogleVR SDK so that I'm using an Event Trigger for when the midpoint of the VR-screen enters the cube. When this happens, my custom method LookAtCube()
is triggered.
I want it to make that the cube keeps rotating. I can rotate with the transform.Rotate-function
, but the problem is that it only rotates for 1 game tick (I think) because the Event I'm triggering on is "Pointer Enter".
My question:
Is there an event that you can trigger that keeps executing the given method when being in the distances of the collider? (for example, when looking at the cube it should rotate, when not looking it should not rotate).
I tried to fix this with a while(true)-loop, but the game simply crashes.
For example on a PC/Standalone application, you can simply use the private method OnMouseOver(). I would like this but then with the focus (midpoint) of the VR screen.
This is what I tried so far (2 examples):
First example: it simply rotates a little bit and stops (so I guess it rotates for 1 game tick at the set speed).
using UnityEngine;
public class MoveCube : MonoBehaviour
{
float rotateSpeed = 0.5f;
// Use this for initialization
void Start()
{
}
public void LookAtCube()
{
transform.Rotate(new Vector3(rotateSpeed, rotateSpeed, rotateSpeed));
}
public void LookOutCube()
{
transform.Rotate(new Vector3(0, 0, 0));
}
}
Second example: I used a boolean that I set true/false respectively when entering/exiting the cube. Then the while loop should keep it rotating, but the game crashes (can't see the error message since it totally crashes, but I guess an overflowexpection).
using UnityEngine;
public class MoveCube : MonoBehaviour
{
float rotateSpeed = 0.5f;
Boolean hoverState = false;
// Use this for initialization
void Start()
{
}
public void LookAtCube()
{
while(hoverState == true){
transform.Rotate(new Vector3(rotateSpeed, rotateSpeed, rotateSpeed));
}
}
public void LookOutCube()
{
hoverState = false;
transform.Rotate(new Vector3(0, 0, 0));
}
}
Any ideas on how to implement it correctly? Thanks in advance!
You will run into infinite loop here:
while(hoverState == true)
{
transform.Rotate(new Vector3(rotateSpeed, rotateSpeed, rotateSpeed));
}
That's because you're not waiting for a frame and other scripts won't get chance to run.
You need to use the Update
function since it runs every frame. Set hoverState
to true
"Pointer Enter" event and false
in "Pointer Exit" event then use hoverState
in the Update
function to determine when to rotate the GameObject.
float rotateSpeed = 0.5f;
bool hoverState = false;
public void LookAtCube()
{
hoverState = true;
}
public void LookOutCube()
{
hoverState = false;
}
void Update()
{
if (hoverState)
transform.Rotate(new Vector3(rotateSpeed, rotateSpeed, rotateSpeed));
}