(1 / 180º) = (direction / rotationAroundAxis)
They are calculated using this very advanced mathematical formula: RotationAroundYAxis and rotationAroundXAxis are the rotations we must add to the current rotation each frame. In each subsequent frames, we calculate direction, which is the difference between the current mousePosition and previousPosition. On the first frame in which the mouse is down (or the finger touches the screen), we store that position as our previousPosition. Vector3 direction = previousPosition - currentPosition įloat rotationAroundYAxis = -direction.x * 180 // camera moves horizontallyįloat rotationAroundXAxis = direction.y * 180 // camera moves vertically Vector3 currentPosition = cam.ScreenToViewportPoint(Input.mousePosition) PreviousPosition = cam.ScreenToViewportPoint(Input.mousePosition)
HOW TO ROTATE DRAWING IN VIEWPORT CODE
This is how the code looks: public class CameraMovement : MonoBehaviour In order to do that, we need to store the previous position in a private field ( previousPosition). Step 2: Calculate the rotationĮvery frame we will calculate how much the cursor/finger moved since last frame, and translate it into how many degrees the camera should rotate according to our previously defined relation:ġ unit in viewport coordinates 180 degrees of camera rotation Now that we have the problem defined and the drag detected, we can move the camera. The Input class also has a convenient mousePosition field which gives us the position of the pointer (mouse or finger) in screen coordinates. We are using the functions Input.GetMouseButtonDown(0) and Input.GetMouseButton(0) to detect whether the user clicked/tapped or dragged the pointer over the screen.
HOW TO ROTATE DRAWING IN VIEWPORT UPDATE
(It is also good practice not to handle it in the Update function directly, but this is the smallest of projects and we're not going to over-engineer it.) In Unity games, it is common practice to use the Update function to detect player input. Will be true as long as the mouse is down or a touch is happening. Will be true only in the 1st frame in which it detects the mouse is down (or a tap is happening) Open CameraMovement.cs with your editor, time to code! public class CameraMovement : MonoBehaviour Of course you can arrange your files and classes however you prefer.) (This is the most basic setup working with an empty project.
This created a " CameraMovement.cs" file in your Assets folder, which contains an empty CameraMovement class that extends MonoBehaviour.