- Home /
How to make camera move like it does in the scene viewport?
I want to make my main camera move around like it does in the inspector window.
When middle mouse button is held, pan the camera left and right, regardless of rotation
When the scroll wheel is moving up, zoom forward. When scroll is moving down, zoom back, regardless of rotation
When right mouse button is held, rotate the camera on its own axis on x and y
You can see that I made emphasized "regardless of rotation." Currently, I have a script that quickly gets the job done. However, If I rotate so that my camera is rotated 90 degrees to the right for example, the code doesn't work as anticipated, like the panning for example.
I understand that this is the issue because I am strictly modifying the x and y values of the transform's position. However, when rotating an object, my panning logic still moves the camera on the x and y axis-- which is wrong since "left/right, up/down" change when rotating.
What can I do to fix this?
Here's my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCamera: MonoBehaviour
{
// Panning fields
private const float speed = 0.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// Panning
if(Input.GetMouseButton(2))
{
// Get the mouse movement value in x and y, and apply it to our camera's position
float dx = -Input.GetAxisRaw("Mouse X") * speed;
float dy = -Input.GetAxisRaw("Mouse Y") * speed;
transform.localPosition += new Vector3(dx, dy, 0.0f);
}
// Zooming
transform.position += new Vector3(0.0f, 0.0f, Input.GetAxisRaw("Mouse ScrollWheel") * speed * 2.0f);
// Rotation
if(Input.GetMouseButton(1))
{
float rx = Input.GetAxisRaw("Mouse Y") * speed * 2.0f;
float ry = -Input.GetAxisRaw("Mouse X") * speed * 2.0f;
Vector3 temp = transform.eulerAngles;
temp.x = transform.eulerAngles.x + rx;
temp.y = transform.eulerAngles.y + ry;
transform.eulerAngles = temp;
}
}
}
Your answer
Follow this Question
Related Questions
Move camera when mouse is near the edges of the screen 1 Answer
Need help updating camera position to go above the player 2 Answers
How do I get camera movement through controller input. 1 Answer
How can i fix a position of a gameobject after it meets its condition 1 Answer
camera follow obect on pan to z axis 0 Answers