1
\$\begingroup\$

I'm new to Unity and c# but have programming experience... I have a a simple "game" in Unity that shows one sphere orbiting another. How do I allow the camera to be moved by the user in a "free look" dynamic? I want to be able to press the right mouse button and adjust the camera on two axes. I'm using Unity 5.0. Whenever I run the following Unity freezes when I press the right mouse button.

Here's the camera control script:

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour 
{
     private float horizontalSpeed;
     private float verticalSpeed;

     void Update () 
     {
           while (Input.GetMouseButtonDown(1))
           {
                 horizontalSpeed = Input.GetAxis ("Mouse Y");
                 verticalSpeed = Input.GetAxis ("Mouse X"); 
                 transform.Translate(verticalSpeed,horizontalSpeed,0.0f);
           }
     }
}
\$\endgroup\$
2
\$\begingroup\$

Update runs once per frame. Using while in the update script like that, in English reads like this: "Once for this frame, while the mouse button was held down for this frame, move the camera and stuff". The reason why this does not work well is because, the mouse will be in a 'down' state until the next frame, and it wont go onto the next frame until the mouse is not in a down state and instead will run what is in your while loop, and because of that, the next frame will need to wait until the while loop is completed (and that loop is waiting for the next frame before it is finished) --- and this logical loop causes unity to freak out (technically it's just spinning) and crash.

What you want to do, is have the camera update it's position each frame. To accomplish this it is relatively easy...

void Update () 
{
    if (Input.GetMouseButton(1))
    {
        transform.Translate(-Input.GetAxis ("Mouse X"),-Input.GetAxis ("Mouse Y"),0.0f);
    }
}

What that says now is: "If the button has been pressed this frame, move it by how much it moved this frame".

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.